ccsun2 :c-course % cat -n string.cpp 1 //string.cpp 2 ///by tsaiwn@csie.nctu.edu.tw 3 #include 4 #include 5 //////// 以上要新版 C++ 才能用 !!! 6 //////// C++ 字串 不同於 C 7 /////////// 以下是 C 的東東 8 extern "C"{ 9 #include 10 #include 11 } 12 using namespace std; ////////////// all LIB now in "std" namespace 13 int main() 14 { char t[80]; 15 string x("I am a string."); 16 cout << "x=" << x << endl; 17 cout << "do strcpy(t, x.c_str() );" << endl; 18 strcpy(t, x.c_str() ); //轉成 C 的字串 19 printf("t=%s\n", t); 20 printf(" length of t=%d\n", strlen(t)); 21 string y(t); // 再轉成 C++ 字串看看 22 23 cout << "do string y(t); " << endl; 24 25 cout << "C++ String y=" << y << endl; 26 cout << "it's size= y.size() = " << y.size() << endl; 27 28 cout << " y = y + \" Do you get it?\"; " << endl; 29 30 y = y + " Do you get it?"; 31 32 cout << "new y=" << y << endl; 33 cout << "new size=" << y.size() << endl; 34 } ccsun2 :c-course % g++ string.cpp ccsun2 :c-course % ./a.out x=I am a string. do strcpy(t, x.c_str() ); t=I am a string. length of t=14 do string y(t); C++ String y=I am a string. it's size= y.size() = 14 y = y + " Do you get it?"; new y=I am a string. Do you get it? new size=29 ccsun2 :c-course % exit exit