順序輸出給定字符串中所出現過的大寫英文字母,每一個字母只輸出一遍;若無大寫英文字母則輸出「Not Found」。ios
輸入格式:
輸入爲一個以回車結束的字符串(少於80個字符)。
輸出格式:
按照輸入的順序在一行中輸出所出現過的大寫英文字母,每一個字母只輸出一遍。若無大寫英文字母則輸出「Not Found」。spa
輸入樣例1:code
FONTNAME and FILENAME
輸出樣例1:blog
FONTAMEIL
輸入樣例2:ci
fontname and filrname
輸出樣例2:字符串
Not Found
(摘自pintia.cn)get
解答:編譯器
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 bool isMajuscule(char); //用於判斷字符類型的形參是否爲大寫字母 5 int main() 6 { 7 string str,result; //str爲輸入的字符串,result爲結果 8 unsigned i(0),j(0); //定義無符號類型變量,能夠替換爲int型 9 getline(cin,str); //獲取一整行字符串,用於接收帶有空格的字符串 10 while(i<str.length()) 11 { 12 if(isMajuscule(str[i])) 13 { 14 bool flag(true); //str[i]已經存在(不須要添加)則爲false,不存在(須要添加)則爲true 15 for(unsigned k(0);k<j;k++) //判斷str[i]是否在result中存在 16 { 17 if(str[i]==result[k]) 18 flag=false; 19 } 20 if(flag) 21 { 22 char ch(str[i]); 23 result=result+ch; //向result添加字符 24 j++; 25 } 26 } 27 i++; 28 } 29 if(result.length()) cout<<result; //若是result不爲空,則輸出result 30 else cout<<"Not Found"; //result爲空,則輸出"Not Found" 31 return 0; 32 } 33 inline bool isMajuscule(char ch) 34 { 35 if(ch>='A'&&ch<='Z') return true; //判斷ch是否在'A'和'Z'之間,即判斷ch是否爲大寫 36 else return false; 37 }
解析:string
見代碼註釋。io
因爲string.length()的返回值爲unsigned類型變量,所以使用返回值於int型變量比較時,編譯器會報‘warning’,但不影響正確性。
字符串類型的變量可使用'+',用於鏈接字符串。