c++ - c_str 函数有什么用?

标签 c++ c string c-str

我的理解是 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");
}

See it in action

注意事项:

¹ 这并不完全正确,因为 std::string(与 C 字符串不同)可以包含 \0 字符。如果是这样,接收 c_str() 的返回值的代码会误以为字符串比实际短,因为它会解释 \0作为字符串的结尾。

关于c++ - c_str 函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416445/

相关文章:

将 void* 转换为二维数组

c - 使用 C 中的指针在字符串数组中出现段错误

string - Haskell:检查字符串中的元音

c++ - 为虚拟文件添加属性

c++ - 链接器提示 vtable 上的 undefined reference

c++ - 将 int 放入 char 数组中是否需要放置 new 合法?

c - 使用OpenMP计算PI值

c++ - 确定树的内部路径长度 (C++)

c - getdate.y语法疑惑

PHP 检查字符串是否包含单词之间的空格(不在开头或结尾)