2017年12月4日 星期一

[C_ST56-易] 字串轉換(C++)

[C_ST56-易] 字串轉換

問題描述
假設每個英文字母都有一個與其互補的英文字母,如 [A/a] 的互補字母為 [Z/z] 、 [B/b] 的互補字母為 [Y/y] 以此類推。再將每個英文字母給定一個數值 , 無論其大小寫,如 [A/a]=1 、 [B/b]=2 、 [C/c]=3 、…、 [Z/z]=26 。當輸入一連串大小寫英文字母雜湊的字串,請將這字串全部轉成其互補字母反序印出並將輸入字串內的英文字母轉為數字算出總和。
輸入格式 
輸入 一英文字串。
輸出格式 
輸出 互補字串並算出原字串的數字和 。
Example
Sample Input:Sample Output:
abc
xYz
zyx 6
cBa 75


  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main() {  
  5.     // [C_ST56-易] 字串轉換  
  6.     string text;  
  7.     int len;//字串長度  
  8.     int sum = 0;//加總  
  9.     while(cin >> text)  
  10.     {  
  11.         len = text.size();  
  12.         char c_text[len];  
  13.         for(int i = 0;i < len;i++)  
  14.         {  
  15.             if(65 <= (char)text[i] && (char)text[i] <= 90)//大寫  
  16.             {  
  17.                 sum = sum + (text[i]-64);  
  18.                 //計算原字串的數字和  
  19.                 c_text[i] = 'Z' - (text[i]-'A');  
  20.                 //互補字串  
  21.             }  
  22.             else if(97 <= (char)text[i] && (char)text[i] <= 122)//小寫  
  23.             {  
  24.                 sum = sum + (text[i]-96);  
  25.                 //計算原字串的數字和  
  26.                 c_text[i] = 'z' - (text[i]-'a');  
  27.                 //互補字串  
  28.             }  
  29.         }  
  30.         //輸出  
  31.         for(int i = 0;i < len;i++)  
  32.         {  
  33.             cout << c_text[i];  
  34.         }  
  35.         cout << " " << sum << endl;  
  36.         sum = 0;  
  37.     }  
  38.     return 0;  
  39. }  

沒有留言:

張貼留言