什么是使用c_str函数在C ++中 [英] What is use of c_str function In c++
问题描述
我刚开始读C ++,发现C ++具有它C没有字符串操作功能丰富。我读这些功能,并在 c_str()
键,从我的理解是 c_str
转换可能是一个字符串来空终止,也可能不是一个空结尾的字符串。是真的吗?
I have just started reading C++ and found c++ having rich functions for string manipulation which C does not have. I am reading these function and came across c_str()
and from what I understand is c_str
convert a string which may be null terminated or may not be to a null terminated string .Is it true?
任何人都可以建议我一些示例,这样我可以了解采用的 c_str 函数??
Can anyone suggest me some example so that i can understand the use of c_str function??
推荐答案
c_str
返回为const char *
的指向空结尾的字符串(如C风格的字符串)。当你想传递一个的std ::字符串
来一个函数,愿与C风格的字符串工作的内容¹是有用的。
c_str
returns a const char*
that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string
to a function that expects to work with a C-style string.
例如,考虑这个code:
For example, consider this code:
std::string str("Hello world!");
int pos1 = str.find_first_of('w');
int pos2 = strchr(str.c_str(), 'w') - str.c_str();
if (pos1 == pos2) {
printf("Both ways give the same result.\n");
}
See it in action.
注:
¹这是不完全正确,因为的std ::字符串
(不像C字符串),可以包含 \\ 0
字符。如果确实如此,接收c_str 的返回值code()
会误以为该字符串比它短真的是,因为它会间preT \\ 0
作为字符串的结尾。
¹ This is not entirely true because an std::string
(unlike a C string) can contain the \0
character. If it does, the code that receives the return value of c_str()
will be fooled into thinking that the string is shorter than it really is, since it will interpret \0
as the end of the string.
这篇关于什么是使用c_str函数在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!