Board logo

標題: 字串處理 (一) [打印本頁]

作者: tonyh    時間: 2015-12-5 10:11     標題: 字串處理 (一)

本帖最後由 tonyh 於 2015-12-5 11:12 編輯

我們在宣告字元陣列的時候要注意它的長度,以免位數不夠造成程式錯誤。事實上,每個字串後面都有一個 '\0' 的字元,例如 "tw" 字串,事實上總共用了 3 Bytes,若為中文字,則每個字要佔兩個字元
例如:
char str[3]="tw";
char str[9]="字串處理"
分別利用宣告字串與宣告字元陣列的方式, 在銀幕上顯示 "Good morning!" 字樣.
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     string str1="Good morning!";
  7.     char str2[]="Good morning!";
  8.     cout<<str1<<endl;
  9.     cout<<str2<<endl;
  10.     cout<<str1[0]<<endl;
  11.     cout<<str2[1]<<endl;
  12.     system("pause");
  13.     return 0;   
  14. }
複製代碼

作者: 洪振庭    時間: 2015-12-5 11:16

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     string str1="Good morning!";
  7.     char str2[]="Good morning!";
  8.     cout<<str1<<endl;
  9.     cout<<str2<<endl;
  10.     cout<<str1[0]<<endl;
  11.     cout<<str2[1]<<endl;

  12.     system("pause");
  13.     return 0;   
  14. }
複製代碼

作者: 李知易    時間: 2015-12-5 11:20

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     string str1="Elephant";
  7.     char str2[]="Study";
  8.     cout<<str1<<endl;
  9.     cout<<str2<<endl;
  10.     cout<<str1[0]<<endl;
  11.     cout<<str2[1]<<endl;
  12.     system("pause");
  13.     return 0;   
  14. }
複製代碼

作者: 梁和雋    時間: 2015-12-5 11:26

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     string str1="Good morning!";
  7.     char str2[]="Good morning!";
  8.     cout<<str1<<endl;
  9.     cout<<str2<<endl;
  10.     cout<<str1[0]<<endl;
  11.     cout<<str2[1]<<endl;
  12.     system("pause");
  13.     return 0;   
  14. }
複製代碼





歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://seed.istak.org.tw/) Powered by Discuz! 7.2