红安话方言段子:高分悬赏 统计输入的字符串中字母的频率

来源:百度文库 编辑:高考问答 时间:2024/05/04 15:00:21
各位高手帮小弟编个程序啊

统计输入的字符串中字母的频率

从键盘上输入一个字符串,该字符串全部由英语字母组成,长度不超过30个字符,以“%”字符作为输入结束的标志(字符“#”不作为字符串的字符)。要求程序能够完成:
1.输入时若输入了字母或“#”以外的字符,应给出出错信息,重新输入。
2.统计输入字符串中没个字母出现的次数,并按次数值由大到小的顺序输出结果
多谢了 不知道能用java的apletd 形式写吗?
回答之后有重赏

#define MAX_LEN 30
int main(int argc, char **argv)
{
int i, j, k, temp;
char a[MAX_LEN+1];
char c;
int num[26] = {0};
int rank[26] = {0};

i = 0;
printf("Enter the string, % to terminate : \n");
while((c = getchar()) != '%' && i < MAX_LEN)
{
if(c >= 'a' && c <= 'z')
{
a[i] = c;
num[c-'a']++;
i++;
}
else if(c >= 'A' && c <= 'Z')
{
a[i] = c;
num[c - 'A']++;
i++;
}
else if(c == '#')
{
printf("Error: # is not allowed.\n");
}
else if(c != '\n')
{
printf("Error: only english letter allowed, you entered %c.\n", c);
}
}
a[i] = 0;
printf("You entered :%s\n", a);
//sort
for(i = 0; i < 26; i++)
{
rank[i] = i;
}

//selection sort
for(i = 0; i < 26; i++)
{
k = i;
for(j = i + 1; j < 26; j++)
{
if(num[rank[j]] > num[rank[k]]) k = j;
}
if(k != i)
{
temp = rank[i];
rank[i] = rank[k];
rank[k] = temp;
}
}

for(i = 0; i < 26; i++)
{
if(num[rank[i]] > 0)
printf("%c : %d\n", 'a' + rank[i], num[rank[i]]);
}

return 0;
}

不好意思,之前的版本没有按顺序输出,下面的测试通过了:
#define MAX_LEN 30
int main(int argc, char **argv)
{
int i, j, k, temp;
char a[MAX_LEN+1];
char c;
int num[26] = {0};
int rank[26] = {0};

i = 0;
printf("Enter the string, % to terminate : \n");
while((c = getchar()) != '%' && i < MAX_LEN)
{
if(c >= 'a' && c <= 'z')
{
a[i] = c;
num[c-'a']++;
i++;
}
else if(c >= 'A' && c <= 'Z')
{
a[i] = c;
num[c - 'A']++;
i++;
}
else if(c == '#')
{
printf("Error: # is not allowed.\n");
}
else if(c != '\n')
{
printf("Error: only english letter allowed, you entered %c.\n", c);
}
}
a[i] = 0;
printf("You entered :%s\n", a);
//sort
for(i = 0; i < 26; i++)
{
rank[i] = i;
}

//selection sort
for(i = 0; i < 26; i++)
{
k = i;
for(j = i + 1; j < 26; j++)
{
if(num[rank[j]] > num[rank[k]]) k = j;
}
if(k != i)
{
temp = rank[i];
rank[i] = rank[k];
rank[k] = temp;
}
}

for(i = 0; i < 26; i++)
{
if(num[rank[i]] > 0)
printf("%c : %d\n", 'a' + rank[i], num[rank[i]]);
}

return 0;
}

根据你的要求改改吧。

用C++写的程序,没有经过调试。
但是思想有了,望高手指点,不胜感激。
^_^
#include<iostream.h>
void main ()
{
char a[100];
int i=0;
int j=0;
while (a[i]!=% && i<30)
{
cin>>a[i];
if(!(a[i]>=65&&a[i]<=90||a[i]>=97&&a[i]<=122||a[i]=35))
cout<<"输入错误的字符"<<endl;
if(a[i]>=65&&a[i]<=90||a[i]>=97&&a[i]<=122)
i++; //字母的个数
j++; //数组的元素的个数
}
cout<<"没有出现字母的次数试:"<<j-i;
for(int m=0;m<j-1;m++)
{for(int n=1; n<j;n++) //排序
{
if(a[m]<a[n])
{
char R= a[m];
a[m]=a[n];
a[n]=R; //交换
}
}}
for(int i=0,i<j,i++) // 输出
cout<<a[i]<<" ";
cout<<endl;
}