返回列表 發帖

陣列 (三) - 字元陣列與字串 1

本帖最後由 tonyh 於 2015-8-28 21:09 編輯

在C++中,字串可運用字元陣列或字串變數來處理。在利用字元陣列宣告字串的時候要注意它的長度,以免位數不夠造成程式錯誤。事實上,每個字串後面都有一個 '\0' 的字元,例如 "tw" 字串,事實上總共用了 3 Bytes,若為中文字,則每個字要佔兩個字元,這一點要特別注意。
char myName[3] = "tw";
char myName[7] = "王小明";

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     char str1[19]="大家好!我叫王小明!";
  7.     //一個中文字佔2字元,一個英文字佔1字元,結尾的\0佔1字元
  8.     string str2="大家好!我叫王小明!";
  9.     cout<<str1<<endl;
  10.     cout<<str2<<endl;
  11.     system("pause");
  12.     return 0;   
  13. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.         char str[] = "大家好 ! 我叫王小明 ! ";
  7.         cout<<str<<endl;
  8.         system("pause");
  9.         return 0;
  10. }
複製代碼

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main(){
  5.     char str[]="大家好!我要沈子耕!";
  6.     cout<<str<<endl;
  7.     system("pause");   
  8.     return 0;
  9. }
複製代碼
ABCDEFGHIJKLMNOPQRSTUVWXYZ

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     char str[]="大家好!我叫王八蛋!";
  7.     cout<<str<<endl;
  8.     system("pause");
  9.     return 0;   
  10. }
複製代碼

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     char str1[]={"大家好我叫王小明"};
  7.     string str2="大家好我叫王小明";
  8.     cout<<str1<<endl;
  9.     cout<<str2<<endl;
  10.     system("pause");
  11.     return 0;   
  12. }
複製代碼

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     char myName[7] = "王小明";
  7.     cout<<myName<<endl;
  8.     system("pause");
  9.     return 0;   
  10. }
複製代碼

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     char str1[19]="大家好!我叫王小明!";
  7.     string str2="大家好!我叫王小明!";
  8.     cout<<str1<<endl;
  9.     cout<<str2<<endl;
  10.     system("pause");
  11.     return 0;   
  12. }
複製代碼
我是眾神之王XXX  I love you
0000000000

TOP

返回列表