题目
输入n行文本,并统计其中字母的个数
例如:
输入:2
hello
hello
输出:
e 2
h 2
l 4
o 2
长度为5的字母有2个
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <cstring>
using namespace std;
void toLower(char (*prt)[100],int row){
//将所有字符小写化
for(int i=0;i<=row;i++)
for(int j=0;prt[i][j]!='\0';j++)
if(prt[i][j]>='A' && prt[i][j]<='Z')
prt[i][j] = prt[i][j]-'A'+'a'; //转换为小写字母
}
void printLetter(int a[],int n){
cout<<"字母的个数如下:"<<endl;
for(int i=0;i<26;i++)
cout<<setw(5)<<left<<static_cast<char>(i+'a')
<<setw(5)<<left<<a[i]<<endl;
}
void totalLen(char (*p)[100],int a[],int l){
//参数表:文本数组,个数统计数组,行数
char* temp;
for(int i=0;i<l;i++){
temp = strtok(p[i]," ,.\n");
while(temp!=NULL){
a[strlen(temp)]++;
temp = strtok(NULL," ,.\n");
}
}
}
void printLetterLen(int a[]){
for(int i=0;i<20;i++){
if(a[i]!=0)
cout<<"长度为 "<<i<<" 的字母有 "<<a[i]<<" 个"<<endl;
}
}
int main()
{
int n,total[26]={0},len[20]={0};
cout << "Entet n rows text: ";
cin>>n;
cout<<"please enter text: "<<endl;
char text[n][100];
getchar(); //这里如果不加getchar,回车会直接把第一行吃掉
for(int i=0;i<n;i++){
cout<<i+1<<" row is:";
cin.getline(text[i],100);
}
toLower(text,n); //将所有字母小写化
//开始逐行统计
for(int i=0;i<n;i++)
for(int j=0;text[i][j]!='\0';j++)
total[text[i][j] - 'a']++;
//统计不同长度的字母个数
totalLen(text,len,n);
//输出字母个数表
printLetter(total,n);
cout<<endl;
//输出不同长度字母的个数
printLetterLen(len);
return 0;
}