我有一个 C++ string
。我需要将此字符串传递给接受 char*
参数的函数(例如 - strchr()
)。
a) 我如何获得该指针?
b) 是否有一些等同于 strschr()
的函数适用于 C++ 字符串
?
最佳答案
- 获取
C
字符串等价于C++
string
对象使用c_str
函数。 - 定位第一次出现的a
char
在string
对象中使用find_first_of
功能。
例子:
string s = "abc";
// call to strlen expects char *
cout<<strlen(s.c_str()); // prints 3
// on failure find_first_of return string::npos
if(s.find_first_of('a') != string::npos)
cout<<s<<" has an a"<<endl;
else
cout<<s<<" has no a"<<endl;
注意:我给出的 strlen
只是一个采用 char*
的函数示例。
关于c++ - 如何将 char* 指针转换为 C++ 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707980/