"); //-->
1、c_str():生成一个const char*指针,指向以空字符终止的数组。
参考自:csqlwy - 博客园
链接:www.cnblogs.com/qlwy/archive/2012/03/25/2416937.html(点击尾部阅读原文前往)
①因为c_str()返回的只是一个指向某字符串的指针,因此要么现用先转换,要么把它的数据复制到用户自己可以管理的内存中
int main() { const char* c; string s="1234"; c = s.c_str(); cout<<c<<endl; //输出:1234 s="abcd"; cout<<c<<endl; //输出:abcd return 0; }12345678910
我们可以使用strcpy等函数把需要的数据拷贝到另一个内存中,就能独立开来。(推荐)。
int main() { char* c=new char[20]; string s="1234"; //c = s.c_str(); strcpy(c,s.c_str()); cout<<c<<endl; //输出:1234 s="abcd"; cout<<c<<endl; //输出:1234 return 0; }1234567891011
② c_str()返回一个客户程序可读不可改的指向字符数组的指针,不需要手动释放或删除这个指针。
2、data():与c_str()类似,但是返回的数组不以空字符终止。
3、copy(p,n,size_type _Off = 0):从string类型对象中至多复制n个字符到字符指针p指向的空间中。默认从首字符开始,但是也可以指定,开始的位置(记住从0开始)。返回真正从对象中复制的字符。------用户要确保p指向的空间足够保存n个字符。
(从size_type _Off开始,赋值n个字符到p中)
int main( ) { using namespace std; string str1 ( "1234567890" ); basic_string <char>::iterator str_Iter; char array1 [ 20 ] = { 0 }; char array2 [ 10 ] = { 0 }; basic_string <char>:: pointer array1Ptr = array1; basic_string <char>:: value_type *array2Ptr = array2; cout << "The original string str1 is: "; for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ ) cout << *str_Iter; cout << endl; basic_string <char>:: size_type nArray1; // Note: string::copy is potentially unsafe, consider // using string::_Copy_s instead. nArray1 = str1.copy ( array1Ptr , 12 ); // C4996 cout << "The number of copied characters in array1 is: " << nArray1 << endl; cout << "The copied characters array1 is: " << array1Ptr << endl; basic_string <char>:: size_type nArray2; // Note: string::copy is potentially unsafe, consider // using string::_Copy_s instead. nArray2 = str1.copy ( array2Ptr , 5 , 2 ); // C4996 cout << "The number of copied characters in array2 is: " << nArray2 << endl; cout << "The copied characters array2 is: " << array2Ptr << endl; }1234567891011121314151617181920212223242526272829303132
*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。