tags: FoShiShi

ASCII

What

ASCII
全名American Standard Code for Information Interchange
中文名為美國標準資訊交換碼
是基於拉丁字母的一套電腦編碼系統

ASCII碼用了0 ~ 127個數字來儲存大小寫英文字母,阿拉伯數字,

When

在我們要去計算字元間的變換
例:
像在一個字串中把所有英文字母變成下一個(A -> B, B -> C Z -> A)
一定會用到ASCII來轉換字元

How

ASCII表

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 →

看十進位對字符就可以了
十六進位不用看

0 ~ 31127格的字元我們基本上不太會用到
剩下的就是真正會用到的部分

我們會發現,ASCII很聰明的把連續的英文字母跟數字排在一起,這樣就可以透過ASCII的加減實現英文字母的加減

型態轉換

只要在一個字元的名稱前面加上(int)就能夠將其轉為他的ASCII
相反的,只要在一個數字(ASCII表的範圍中)的名稱前面加上(char)就可以將其轉為字元

例:

char chr = 'A'; cout << (int)chr << endl; // 65 int ascii = (int)(chr + 2); cout << (char)ascii << endl; // C

實際應用

題目1

輸入一字串str
其中只包含大寫英文字母
將其每個字母變為下一個字母
(A -> B, B -> C, , Z -> A)
然後輸出

solution

可以依序把每個英文字母的ASCII減掉41('A'的ASCII)
這樣就會變成:
A = 0, B = 1, ... , Z = 25
這樣如果Z+1後可以% 26變回A

#include<iostream> using namespace std; int main() { string str; cin >> str; for(int i = 0; i < str.length(); i ++ ) { int num = int(str[i]) - int('A'); num = (num + 1) % 26; str[i] = char(int('A') + num); } cout << str << endl; }