字元

字元的宣告與儲存

char為字元的資料型態。電腦儲存字元時,以二進位的方式儲存,每個字元佔 1 Byte 的記憶體空間。

char c = 'A'; //宣告字元變數c, 設定為'A'

字元的表示-ASCII code

電腦表示字元時,先將二進位轉成數字,再透過對應表對應的數字。找到目前國際通用的對應表為ASCII code (美國資訊交換標準代碼)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

除了透過查表,我們也可以透過以下程式測試輸入的字元對應的ascii

#include <iostream> using namespace std; int main(){ char c; cin >> c; cout << (int)c << endl; return 0; }

我們可以從觀察ascii code的規則可以得知,大寫字母小寫字母以及數字在表中都是連續存在的。
所以我們可以透過數學的計算與判斷處理字元。以下舉幾個例子:

  • 從字元0~9 變成數字 0~9: c-'0'
  • 從字元A~Z 變成數字 0~25: c-'A'
  • 判斷是否為大寫字母: c >= 'A' && c <= 'Z'

字串與字元陣列

範例輸入/輸出
輸入 輸出
A123456789 A123456789

字串(string)

#include <iostream> using namespace std; int main(){ string s; cin>>s; for(int i=0; i<10; i++){ cout << s[i]; } return 0; }

字元陣列(char array)

char c[10]; for(int i=0; i<10; i++){ cin >> c[i]; } for(int i=0; i<10; i++){ cout << c[i]; }