返回列表 發帖

字串處理 (一)

本帖最後由 tonyh 於 2013-12-14 15:38 編輯

我們在宣告字串的時候要注意它的長度,以免位數不夠造成程式錯誤。事實上,每個字串後面都有一個 '\0' 的字元,例如 "tw" 字串,事實上總共用了 3 Bytes,若為中文字,則每個字要佔兩個字元。
例如:
char str[3]="tw";
char str[9]="字串處理";
  1. //字串處理 (4種方式)
  2. #include<iostream>
  3. #include<cstdlib>
  4. using namespace std;
  5. int main()
  6. {
  7.     string str1="Hello! My name is Tony!";
  8.     cout<<str1<<endl;
  9.    
  10.     char str2[7]={"Hello!"};
  11.     cout<<str2<<endl;

  12.     char str3[6]={'H','e','l','l','o','!'};
  13.     for(int i=0; i<=5; i++)
  14.         cout<<str3[i];
  15.     cout<<endl;
  16.    
  17.     string str4[5]={"Hello! ","My ","name ","is ","Tony!"};
  18.     for(int i=0; i<=4; i++)
  19.         cout<<str4[i];
  20.     cout<<endl;
  21.    
  22.     system("pause");
  23.     return 0;   
  24. }
複製代碼

返回列表