插入字符串
【问题描述】从键盘输入一个字符串,并在串中的第一次出现的最大元素后边插入字符串”ab”。
【输入形式】任意输入一个字符串
【输出形式】在串中的最大元素后边插入字符串”ab”
【样例输入】123csCUMT
【样例输出】123csabCUMT
【样例说明】为了保证输入的字符串有空格,请使用cin.getline(char* , int);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include<iostream> using namespace std; int main() { int maxnum=0,maxwhere=0,i; char str[500]; cin.getline(str,500); for(i=0;str[i]!='\0';i++) { if((int)str[i]>maxnum) { maxnum=(int)str[i]; maxwhere=i; } } for(i=0;i<=maxwhere;i++) cout << str[i]; cout << "ab"; for(i=maxwhere+1;str[i]!='\0';i++) cout << str[i]; return 0; }
|
统计整数个数
【问题描述】输入一个字符串,其包括数字和非数字字符,如:a123x456 17935? 098tab,将其中连续的数字作为一个整数,依次存放到数组a中,统计共有多少个整数,并输出这些数。
【输入形式】数字和非数字字符的字符串
【输出形式】1)整数个数2)分别输出整数
【样例输入】a123x456 17935? 098tab583【注意需要保留带有空格的字符串,请不要使用gets,cin,练习使用cin.getline(char *str, int maxnum)】
【样例输出】
5
123
456
17935
98
583
【样例说明】第一个输出项为整数的个数,后面的分别为具体的整数。注意,不需要输出提示类文字,如:“整数为”,“分别为”等字样。直接输出结果。有一个数字的也要输出。测试用例中没有超过整数范围连续数字。当遇到0开头的数字应舍去0。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include<iostream> using namespace std; const int MAX=200; int is_num(char c) {return (c>='0'&&c<='9')?1:0;} int main() { char str[MAX]; int total=0; cin.getline(str,MAX); if(is_num(str[0]))total++; for(int i=1;str[i]!='\0';i++) if(is_num(str[i])&&!is_num(str[i-1])) total++; cout << total << endl; for(int i=0;str[i]!='\0';i++) { if(!is_num(str[i])||(str[i]=='0'&&!is_num(str[i-1])&&is_num(str[i+1])))continue; while(is_num(str[i])) cout << str[i++]; cout << endl; } }
|
字符串排序
【问题描述】有5个字符串,首先将它们按照字符串中字符个数由小到大排序,再分别取出每个字符串的第三个字母合并成一个新的字符串输出(若少于三个字符的输出空格)。要求:利用字符串指针和指针数组实现。
【输入形式】5个字符串,用回车分隔
【输出形式】输出一个字符串:按5个字符串中字符个数由小到大排序,再分别取出每个字符串的第三个字母合并成一个新的字符串输出,若少于三个字符的输出空格
【样例输入】
test1234
123test
cumt
think
apples
【样例输出】
cumt think apples 123test test1234
concatenate string:mip3s
【样例说明】输出每个字符串之间用一个空格。字符数量相等的串相对顺序不变。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include<iostream> #include<cstring> using namespace std;
int main() {
char *ch[5]; for(int i=0;i<5;i++) { ch[i]=new char[10]; cin >> ch[i]; } for(int i=0;i<4;i++) for(int j=0;j<5-i-1;j++) { if(strlen(ch[j])>strlen(ch[j+1])) { char *temp=ch[j]; ch[j]=ch[j+1]; ch[j+1]=temp; } } for(int i=0;i<5;i++)cout << ch[i] << " "; cout << endl << "concatenate string:"; for(int i=0;i<5;i++) { if(strlen(ch[i])<3)cout << " "; else cout << ch[i][2]; delete ch[i]; }
return 0; }
|