我有一个C++的string
。我需要将这个字符串传递给接受char*
参数的函数(例如-strchr()
)。
a) 我该如何获得指针?
b) 是否存在一些等效于C++ strings
的strschr()
函数?
a) 使用 string 的 c_str() 函数可以获取指针。 b) 可以使用 std::string 的 find() 函数代替 strchr()。
C++
的 string
对象的 C
字符串等价物,请使用 c_str
函数。string
对象中定位第一个出现的 char
,请使用 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;
注:我只是举了一个接受char*参数的函数strlen作为例子。
Note: I gave the strlen
just an example of a function that takes char*
.
你不能从一个 string
得到一个 char*
。
string
不允许您自由访问其内部缓冲区。您最接近的是使用 .c_str()
得到一个以 null 结尾的 const char*
,或使用 .data()
如果不需要以 null 结尾。
然后,您可以将这些函数返回的指针强制转换为 char*
,但要自行承担风险。话虽如此,只要确保您没有更改字符串,这就是相对安全的转换。如果更改了它,则从 c_str()
得到的指针可能不再有效。
此代码:
string str("Hello World!");
char* sp = (char*)str.c_str();
sp[5] = 'K';
可能是可以的。
但是这个:
string str("Hello World!");
char* sp = (char*)str.c_str();
str = "Chaged string";
sp[5] = 'K';
绝对不可以。
也许这个例子能帮到你
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str ("Replace the vowels in this sentence by asterisks.");
size_t found;
found=str.find_first_of("aeiou");
while (found!=string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}
cout << str << endl;
return 0;
}
str.c_str()
方法获取其中的 char*。c_tsr
不是 c_str
吗?我不是C++专家,但我搜索了一下 c_tsr
,结果纠正为 c_str
。 - Carl Smotriczchar *pw = "Hello world";
char *pw = some_string.c_str()
然而,pw指向的值仅在some_string的生命周期内有效。
更多信息:
如何在C++中将字符串分配给char *pw
祝您好运!
std::string yourString("just an example");
char* charPtr = new char[yourString.size()+1];
strcpy(charPtr, yourString.c_str());
std::vector<char> charBuf(yourString.begin(), yourString.end()); charBuf.push_back('\0');
来避免手动内存管理 - 这将使你能够使用 &charBuf[0]
获取一个 char*
。 - Frerich RaabeC++标准提供了两个std::basic_string类的成员函数,它们返回字符串的第一个元素的指针。它们是c_str()和data()
。但是它们都返回const char *,因此您可能无法将它们与参数类型为char *的函数一起使用。
至于函数strchr,它的第一个参数是。因此,您可以将c_str()和data()与此函数一起使用。但是最好使用sttd::basic_string类的成员函数find()
而不是strchr
。
find_first_of
有一个重载版本,它接受搜索起始位置作为参数。我在这里发布了一个示例:http://www.ideone.com/bESwL - codaddict