c_str()函数的用途是什么?
What is the use of the c_str() function?
我理解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字符串不同)可以包含