c_str()函数的用途是什么?

What is the use of the c_str() function?

本文关键字:是什么 函数 str      更新时间:2023-10-16

我理解c_str将字符串(可能是也可能不是以空结尾的)转换为以空结尾的字符串。

这是真的吗?你能举几个例子吗?

c_str返回指向以空结束的字符串(即c风格字符串)的const char*。当您希望将std::string的"内容"传递给期望使用c风格字符串的函数时,它是有用的。

例如,考虑以下代码:
std::string string("Hello, World!");
std::size_t pos1 = string.find_first_of('w');
std::size_t pos2 = static_cast<std::size_t>(std::strchr(string.c_str(), 'w') - string.c_str());
if (pos1 == pos2) {
    std::printf("Both ways give the same result.n");
}

实际操作

指出:这并不完全正确,因为std::string(与C字符串不同)可以包含字符。如果是这样,接收到c_str()返回值的代码就会误以为字符串比实际长度短,因为它会将解释为字符串的末尾。

在c++中,您将字符串定义为

std::string MyString;

不是

char MyString[20]; .

在编写c++代码时,会遇到一些需要C字符串作为参数的C函数。
像下图:

void IAmACFunction(int abc, float bcd, const char * cstring);

现在有一个问题。您正在使用c++并且正在使用std::string字符串变量。但是这个C函数需要一个C字符串。如何将std::string转换为标准的C字符串?

:

std::string MyString;
// ...
MyString = "Hello world!";
// ...
IAmACFunction(5, 2.45f, MyString.c_str());

这就是c_str()的作用。

注意,对于std::wstring字符串,c_str()返回一个const w_char *

大多数旧的 c++和C函数在处理字符串时使用const char*

通过STL和std::string,引入string.c_str()来实现从std::stringconst char*的转换。

这意味着如果您承诺不更改缓冲区,您将能够使用只读字符串内容。PROMISE = const char*

在C/c++编程中有两种类型的字符串:C字符串和标准字符串。对于<string>头,我们可以使用标准字符串。另一方面,C字符串只是一个普通字符的数组。因此,为了将标准字符串转换为C字符串,我们使用c_str()函数。

例如

// A string to a C-style string conversion //
const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;

输出将是,

Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str
Operation: strlen(cstr1)
The length of C-style string str1 = 17

c_str()将c++字符串转换为C风格的字符串,该字符串本质上是一个以空结束的字节数组。当你想要将一个c++字符串传递给一个需要C风格字符串的函数(例如,很多Win32 API, POSIX风格函数等)时,你可以使用它。

它用于使std::string与需要null终止的char*的C代码互操作。

当你在两个程序之间传输一些字符串对象时,你将使用它。

假设您使用Base64在Python中对某个数组进行编码,然后您想将其解码为c++。一旦你有了从base64解码的字符串,在c++中解码。为了让它返回到浮点数组,您需要做的就是:

float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);