算法之字符串表示数字
分析和思路:用一个新的字符串保存源字符串非数字的数字,在遇到数字时,进行处理
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
主要为了自己学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)