字符串处理大合集

 1 //任意输入字符串,可以包括任何字符。
 2 //1、统计字符串中各个字符的个数,包括空格
 3 //2、去除单词中间多余的空格,包括字符串首尾空格
 4 //3、在数字和字母中间插入字符
 5 //4、将单词提取出来,并统计单词的字母个数
 6 //5、将字母排序,字母大小写的,保持原来先后顺序
 7 //6、将指定的字符串替换为另一个字符串
 8 #include<cstdio>
 9 #include<iostream>
10 #include<cstring>
11 #include<sstream>
12 #include<stdlib.h>
13 using namespace std;
14 int w[210]={0};
15 int judge(char c){
16     if((c>='a'&&c<='z') || (c>='A'&&c<='Z')) return 1;
17     if(c>='0'&&c<='9') return 0;
18 }
19 void Sta(string s){//1、统计字符串中各个字符的个数,包括空格
20     int i;
21     for(string ::iterator it=s.begin();it!=s.end();it++){
22         i=*it;
23         w[i]++;
24     }
25     for(int i=0;i<=210;i++){
26         if(w[i]!=0){
27             printf("%c %d\n",i,w[i]);
28         }
29     }
30 }
31 string deleteSpace(string s){//2、去除单词中间多余的空格,包括字符串首尾空格
32     stringstream ss(s);
33     string t,str;
34     while(ss>>t){
35         str=str+" "+t;
36     }
37     return str.substr(1,str.length()-1);
38 }
39 string Insert(string s,string s1){//在数字和字母中间插入指定字符串
40     string s2;
41     int len=s.length();
42     for(int i=0;i<len;i++){
43         if((judge(s[i])==1 && judge(s[i+1])==0) || (judge(s[i])==0 && judge(s[i+1])==1) && i<len-1){
44             s2+=s[i]+s1;
45             continue;
46         }
47         s2+=s[i];
48     }
49     cout<<s2<<endl;
50     return s2;
51 }
52 string Sta_word(string s){//提取单词,输出每个单词的个数
53     stringstream ss(s);
54     string t;
55     while(ss>>t){
56         cout<<t<<" "<<t.size()<<endl;
57     }
58     return s;
59 }
60 int main(){
61     string str;
62     while(getline(cin,str)){//切记,getline会读取换行符
63         Insert(str,"_");
64     }
65     system("pause");
66     return 0;
67 }

 

posted on 2019-03-11 15:27  Aldrich_2020  阅读(321)  评论(0编辑  收藏  举报