1. 程式人生 > 其它 >演算法之字串表示數字

演算法之字串表示數字

分析和思路:用一個新的字串儲存源字串非數字的數字,在遇到數字時,進行處理

 1 #if 1
 2 #include "iostream"
 3 #include "string"
 4 using namespace std;
 5 int main()
 6 {
 7     string temp;
 8     while (cin>>temp)
 9     {
10         
11         string result ="";
12         result.clear();
13         if(temp.size()==0)
14         {
15 cout<<""<<endl; 16 return 0; 17 } 18 for (int i = 0; i < temp.size(); i++) 19 { 20 21 if ((temp[i] >= 'a'&&temp[i] <= 'z') || (temp[i] >= 'A'&&temp[i] <= 'Z')) 22 { 23 //
result += temp[i] + ""; 24 // char character = 'T'; 25 26 // string tmp_string; 27 // tmp_string.append(1, character); 28 // cout << tmp_string << endl; 29 // string t = "" + temp[i]; 30 result.append(1,temp[i]);
31 } 32 else if ((temp[i] >= '0'&&temp[i] <= '9')) 33 { 34 //result += "*"; 35 result.append(1,'\*'); 36 while ((temp[i] >= '0'&&temp[i] <= '9')) 37 { 38 //result.append(temp[i] + ""); 39 result.append(1, temp[i]); 40 i++; 41 } 42 result.append(1,'\*'); 43 if(i<temp.size()) 44 result.append(1,temp[i]);//處理跳出迴圈的那個字元 45 } 46 else 47 { 48 result.append(1,temp[i]); 49 } 50 51 } 52 53 cout<<result<<endl; 54 } 55 return 0; 56 } 57 #endif 58 59 #if 0 60 #include<iostream> 61 #include<string> 62 63 using namespace std; 64 65 int main(){ 66 67 string str,res; 68 while(cin>>str){ 69 res.clear(); 70 for(int i=0;i<str.size();i++){ 71 if(isdigit(str[i])){ 72 if(i==0) 73 res.append(1,'\*'); 74 75 if(i>0 && !isdigit(str[i-1])) 76 res.append(1,'\*'); 77 78 res.append(1,str[i]); 79 80 if(i<str.size()-1 && !isdigit(str[i+1])) 81 res.append(1,'\*'); 82 83 if(i==str.size()-1) 84 res.append(1,'\*'); 85 } 86 else{ 87 res.append(1,str[i]); 88 } 89 } 90 91 cout<<res<<endl; 92 } 93 94 return 0; 95 } 96 #endif
主要為了自己學習