c_str 函数有什么用?

新手上路,请多包涵

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

这是真的?你能举一些例子吗?

原文由 Amit Singh Tomar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

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 解释为结束细绳。

原文由 Jon 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 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

原文由 Linkon Ruhul 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题