返回列表 發帖

[作業] 字串處理 (一)

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

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

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     string a="小屁孩別鬧";
  7.     char b[]="小屁孩別鬧";
  8.    
  9.    cout<<a<<endl;
  10.    cout<<b<<endl;  
  11.    system("pause");
  12.    return 0;
  13. }
複製代碼

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     char c='A';
  7.     string a="恭喜發財";
  8.     char b[]="恭喜發財";
  9.     cout<<c<<endl;
  10.     cout<<a<<endl;
  11.     cout<<b<<endl;
  12.     system("pause");
  13.     return 0;
  14. }
複製代碼

TOP

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.         string tim="恭喜發財紅包拿來";
  7.         char  tim2 [17]="恭喜發財紅包拿來";
  8.         cout<<tim<<endl;
  9.         cout<<tim2<<endl;
  10.         system("pause");
  11.         return 0;
  12. }
複製代碼

TOP

返回列表