c++ - 如何将 char* 指针转换为 C++ 字符串?

标签 c++ string pointers strchr

我有一个 C++ string。我需要将此字符串传递给接受 char* 参数的函数(例如 - strchr())。

a) 我如何获得该指针?

b) 是否有一些等同于 strschr() 的函数适用于 C++ 字符串

最佳答案

  1. 获取 C 字符串等价于 C++ string 对象使用 c_str 函数。
  2. 定位第一次出现的a charstring 对象中使用 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/

相关文章:

c++ - 将 Matlab 的 bsxfun 转换为 Eigen

c++ - 为什么模板类会有未使用的类型?

c - 字符串格式化时间优化 : pad a line to length K by adding spaces between words

c++ - 在 iPhone xcode 应用程序中,是否可以声明具有全局范围的指针?

c - 为什么这不适用于 C 中的哈希表(指针)

c++ - 代码未编译

c++ - 如何在不分配动态内存的情况下通过函数参数传递正确的字符串?

c++ - float << 通过设置整数部分和浮点部分的精度来操作

string - 如何禁用字符串内的自动关闭单引号?

c - 使用声明的变量初始化数组