语法: const char *c_str(); c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同. 这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。 注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针 比如:最好不要这样: char* c; string s="1234"; c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理 应该这样用: char c[20]; string s="1234"; strcpy(c,s.c_str()); 这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作
再举个例子 c_str() 以 char* 形式传回 string 内含字符串 如果一个函数要求char*参数,可以使用c_str()方法: string s = "Hello World!"; printf("%s", s.c_str()); //输出 "Hello World!"
#include <iostream> #include <cstring> #include <string> using namespace std; int main () { char *cstr,*p; string str ="Please split this phrase into tokens"; //string str ("Please split this phrase into tokens"); cout<<str.size()<< endl; //---36 cstr = new char [str.size()+1]; strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str p=strtok (cstr," "); while (p!=NULL) { cout << p << endl; p=strtok(NULL," ");//分隔strtok("abc,def,ghi",","),最后可以分割成为abc def ghi. } delete[] cstr; system("pause"); return 0; }
输出: Please split this phrase into tokens
strtok /*有个全局的静态指针存储 分割的位置 所以每次调用 就指向下一个 空格*/ 终于理解了 while循环 那边 strtok 不然 永远都是please循环!!!!!