本帖最後由 tonyh 於 2013-12-14 15:38 編輯
我們在宣告字串的時候要注意它的長度,以免位數不夠造成程式錯誤。事實上,每個字串後面都有一個 '\0' 的字元,例如 "tw" 字串,事實上總共用了 3 Bytes,若為中文字,則每個字要佔兩個字元。
例如:
char str[3]="tw";
char str[9]="字串處理";- //字串處理 (4種方式)
- #include<iostream>
- #include<cstdlib>
- using namespace std;
- int main()
- {
- string str1="Hello! My name is Tony!";
- cout<<str1<<endl;
-
- char str2[7]={"Hello!"};
- cout<<str2<<endl;
- char str3[6]={'H','e','l','l','o','!'};
- for(int i=0; i<=5; i++)
- cout<<str3[i];
- cout<<endl;
-
- string str4[5]={"Hello! ","My ","name ","is ","Tony!"};
- for(int i=0; i<=4; i++)
- cout<<str4[i];
- cout<<endl;
-
- system("pause");
- return 0;
- }
複製代碼 |