我的理解是 c_str
将一个可能会或可能不会以 null 结尾的字符串转换为以 null 结尾的字符串。
这是真的吗?可以举一些例子吗?
最佳答案
c_str
返回一个 const char*
,它指向一个以 null 结尾的字符串(即 C 风格的字符串)。当您想将 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 字符串不同)可以包含 \0
字符。如果是这样,接收 c_str()
的返回值的代码会误以为字符串比实际短,因为它会解释 \0
作为字符串的结尾。
关于c++ - c_str 函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416445/