5 字符串分析
作者: 冯向阳时间限制: 1S章节: 其它
问题描述 :
内容:对于任意一个输入的字符串(限定长度在100以内),实现以下功能函数:要求统计其中字符(包括空格)的个数,同时分别指出其中大、小写字母、数字以及其它字符的个数。最后将所有统计结果输出到屏幕上。并编写main函数测试该功能函数。
注意:要求使用指针实现,函数的参数传递采用地址传递、引用传递方式。
函数原型为:
void string_analysis(char *ptr, int &total, int &cap, int &sma, int &num, int &oth);
//total为所有字符的个数,cap为大写字母的个数,sma为小写字母的个数,num为数字的个数,oth为其它字符的个数
main函数可参考以下代码编写:
int main(){
char str[100];
int total,cap,sma,num,oth;
total = cap = sma = num = oth = 0;
cin.get(str,100);
string_analysis(str, total, cap, sma, num, oth);
cout<<cap<<endl;
cout<<sma<<endl;
cout<<num<<endl;
cout<<oth<<endl;
cout<<total<<endl;
return 0;
}
输入说明 :
输入的字符串测试数据位于一行。
输出说明 :
对于测试数据,输出对应的分析结果。
第一行:大写字母的个数
第二行:小写字母的个数
第三行:数字的个数
第四行:其它字符的个数
第五行:所有字符的个数
#include <iostream>
using namespace std;
void string_analysis(char *ptr, int& total, int& cap, int& sma, int& num, int& oth) {
total = cap = sma = num = oth = 0;
while (*ptr != '\0') { // 遍历字符串,直到遇到字符串尾标志'\0'
total++;
if (*ptr >= 'A' && *ptr <= 'Z') { // 大写字母
cap++;
} else if (*ptr >= 'a' && *ptr <= 'z') { // 小写字母
sma++;
} else if (*ptr >= '0' && *ptr <= '9') { // 数字
num++;
} else { // 其它字符
oth++;
}
ptr++;
}
}
int main() {
char str[100];
int total, cap, sma, num, oth;
total = cap = sma = num = oth = 0;
cin.get(str, 100);
string_analysis(str, total, cap, sma, num, oth);
cout << cap << endl;
cout << sma << endl;
cout << num << endl;
cout << oth << endl;
cout << total << endl;
return 0;
}