2017年11月5日 星期日

[C_ST22-易] 迴文字串 II(C++)

**如果看不懂可以在底下留言發問**

**試著看懂別人的程式碼也是一種學習^ ^**

[C_ST22-易] 迴文字串 II

問題描述 :
給予一個英文字母與數字參雜的字串,長度限制在256個字母內。請撰寫一程式輸出此字串的迴文字串,將英文字母大寫改為小寫,小寫改為大寫,數字則不改變。

輸入說明 :
輸入為一個長度在256個字母內的英文字母與數字構成的字串。
輸出說明 :
經轉換後的迴文字串。
範例 :

Sample Input:Sample Output:
bCd1234554321DcB
09876543211234567890

  1. #include <iostream>  
  2. #include <string>  
  3. #include <cmath>  //floor()  
  4. #include <string.h> //strcpy()  
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_ST22-易] 迴文字串 II  
  9.     string text;  
  10.     int count;  
  11.     char change;  
  12.     while(cin >> text)  
  13.     {  
  14.         count = text.size();//string 長度    
  15.         char result[count]; //存入回文結果    
  16.         strcpy(result, text.c_str());//string to char    
  17.         for(int i = 0;i < count;i++) //大小寫轉換  
  18.         {  
  19.             if(90 >= result[i] && result[i] >= 65)//大寫  
  20.             {  
  21.                 result[i] = char(result[i]+32);  
  22.             }  
  23.             else if(122 >= result[i] && result[i] >= 97)//小寫  
  24.             {  
  25.                 result[i] = char(result[i]-32);  
  26.             }  
  27.         }  
  28.           
  29.         for(int i = 0;i < floor(count/2);i++) //迴文  
  30.         {  
  31.             change = result[i];    
  32.             result[i] = result[count-1-i];    
  33.             result[count-1-i] = change;    
  34.         }  
  35.           
  36.         for(int i = 0;i<count;i++)//輸出    
  37.          {    
  38.             if(i == count-1)    
  39.             {    
  40.                 cout << result[i] << endl;    
  41.             }    
  42.             else    
  43.             {    
  44.                 cout << result[i];    
  45.               }    
  46.         }    
  47.     }  
  48.     return 0;  
  49. }  

沒有留言:

張貼留言