字符串统计
【问题描述】
在进行文章重复度检查时,经常需要统计一段英文中的单词数量,并找出长度最长的单词。
设有如下定义:char str[500];
编写程序,通过利用cin.getline(str,500);实现从键盘输入一小段英文(其中可以包含空格,但在同一行),利用函数统计该段英文中包含几个单词,输出统计出的单词数量、最长单词的长度以及长度最长的单词,空格隔开。
注意:函数声明使用void split(char *str);如果有最长的单词不只一个,输出最先找到的那个。
【输入形式】一小段英文,不要超过500个字符
【输出形式】单词数量、最长单词的长度以及长度最长的单词,空格隔开。
【样例输入】welcome to china university of mining and technology
【样例输出】8 10 university
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> using namespace std; void split(char *str) { int num_word=0; int temp=0,maxlen=0,maxwhere=0; for(int i=0;str[i]!='\0';i++) { if(str[i+1]=='\0'&&str[i]>='a'&&str[i]<='z') str[i+1]=' '; if(str[i]==' ') { num_word++; if(temp>maxlen) { maxlen=temp; maxwhere=i-temp; temp=0; } else temp=0; } else { temp++; } } cout << num_word << " " << maxlen << " "; while(str[maxwhere]!=' ') cout << str[maxwhere++];
} int main() { char str[500]; cin.getline(str,500); split(str); return 0; }
|
复数提取
【问题描述】
编写如下原型的函数:
void split(double x,intiPart,doublefPart);
提取出数据x的整数部分与小数部分,分别放于iPart与fPart处,由于形参iPart与fPart都是指针,从而可实现将这两个结果“带回”到主函数中。
在主函数中
输入一个数
输出它的整数部分和小数部分,用空格隔开。
提示:一个double类型数,强制类型转换后就是int,也就是整数部分,差为小数部分。这两个值用指针iPart和指针fPart带回(通过修改指针的目标变量值。)
【输入形式】一个数
【输出形式】整数部分 小数部分,用空格隔开
【样例输入】12.3
【样例输出】12 0.3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include<iostream> using namespace std; void split(double x,int *iPart,double *fPart) { *fPart = x-(int)x; *iPart=(int)x; } int main() { int zhengshu; double xiaoshu,x; cin >> x; split(x,&zhengshu,&xiaoshu); cout << zhengshu << " " << xiaoshu; return 0; }
|
找子串最后一次出现的头字符位置
【问题描述】
编制具有如下原型的函数findLast:
charfindLast(charsourceStr,char*subStr);
findLast函数则要返回源串sourceStr中最后一次出现subStr子字符串的头字符位置。
而后编制主函数,输入两个字符串,将它们用作实参来调用这两个函数,如果返回NULL输出-1,否则输出子字符串出现时头字符在原字符串的下标,每个结果占一行。
要求实现程序中不可使用“string.h”头文件内有关寻找子串的标准库函数。
【输入形式】输入源串sourceStr,子字符串subStr。
【输出形式】子字符串subStr最后一次在源串sourceStr中出现的位置
【样例输入】
welcometochinauniversityofminingandtechnology
in
【样例输出】29
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
| #include<iostream> using namespace std; char*findLast(char*sourcestr,char*substr) { char *ans=NULL; char *temp1,*temp2; for(int i=0;sourcestr[i]!='\0';i++) { if(sourcestr[i]==*substr) { int flag=1; temp1=sourcestr+i; temp2=substr; while(*temp2!='\0') { if(*temp1!=*temp2) flag=0; temp1++;temp2++; } if(flag) ans=sourcestr+i; } } return ans; } int main() { char sourcestr[500],substr[500]; char *ans; cin >> sourcestr >> substr; ans=findLast(sourcestr,substr); if(ans) cout << ans-sourcestr; else cout << -1; return 0; }
|