查找字符频率字符串 [英] Find character frequency in a string
问题描述
我试着去找到字符串中的字符频率,我写了下面code,但它一点儿也不表现出任何output.All我尝试是填补字符数组与各自的计数。
当我试图调试,它的一些如何帮助输出,但输出一些垃圾值。
#包括LT&;&stdio.h中GT;
/ *程序在字符串打印字符频率* /
charcount(字符*,诠释*);
诠释的main()
{
INT N,I = 0;
的printf(输入n);
scanf函数(%d个,&安培; N);
VAR CHAR [N];
诠释计数[100]; //数组存储字频
的printf(请输入字符串:);
fflush(标准输入);
scanf函数(%S,VAR);
charcount(VAR,计数); //调用frequeny功能
对于(i = 0; I< strlen的(数);我++)
{
的printf(%d个\\ N,算[I]);
}
残培();
返回0;
} charcount(字符* P,为int * Q)
{
对于(; * P,P ++)
{
Q [* P] ++;
}
}
您在你的code几个问题:
-
计数
阵列未初始化。 -
您是一个整数阵列上应用的strlen()。
-
计数阵列应该是256(
算[256]
),以涵盖所有可能的ASCII字符。例如,如果你输入ABCD
你会去越界的数组作为D
100 -
您打印错误计数:
的printf(%d个\\ N,算[I]);
应的printf(%d个\\ N,算[ VAR [我]]);
-
申报charcount适当的原型()。
修复这些之后:
#包括LT&;&stdio.h中GT;
/ *程序在字符串打印字符频率* /
无效charcount(字符*,诠释*);
诠释的main()
{
INT N,I = 0;
的printf(输入n);
scanf函数(%d个,&安培; N);
VAR CHAR [N];
诠释计数[256] = {0}; //数组存储字频
的printf(请输入字符串:);
scanf函数(%S,VAR);
charcount(VAR,计数); //调用frequeny功能
对于(i = 0; I<的strlen(VAR);我++)
{
的printf(%d个\\ N,算上[VAR [我]]);
}
返回0;
}无效charcount(字符* P,为int * Q)
{
对于(; * P,P ++)
{
Q [* P] ++;
}
}
请确保在C99或C11编译(如的gcc -std = C99 file.c中
)模式沃拉斯在C早期标准不支持。
Im trying to find character frequency in a string,i wrote the following code,but it does'nt show any output.All im trying is to fill the character array with respective counts.
When i tried to debug,it some how gives output,but prints some garbage value.
#include<stdio.h>
/* Program for printing character frequency in string */
charcount(char *,int *);
int main()
{
int n,i=0;
printf("Enter n :");
scanf("%d",&n);
char var[n];
int count[100]; // array for storing character frequency
printf("Enter string :");
fflush(stdin);
scanf("%s",var);
charcount(var,count); // calling frequeny function
for(i=0;i<strlen(count);i++)
{
printf("%d\n",count[i]);
}
getch();
return 0;
}
charcount(char *p,int *q)
{
for(;*p;p++)
{
q[*p]++;
}
}
You have few problems in your code:
count
array is not initialized.You are applying strlen() on an integer array.
count array should be 256 (
count[256]
) to cover all possible ascii chars. For example, if your input isabcd
you'll go out of bound of array asd
is 100.You are printing the wrong count:
printf("%d\n",count[i]);
should beprintf("%d\n",count[var[i]]);
Declare proper prototype for charcount().
After fixing these:
#include<stdio.h>
/* Program for printing character frequency in string */
void charcount(char *,int *);
int main()
{
int n,i=0;
printf("Enter n :");
scanf("%d",&n);
char var[n];
int count[256]={0}; // array for storing character frequency
printf("Enter string :");
scanf("%s",var);
charcount(var,count); // calling frequeny function
for(i=0;i<strlen(var);i++)
{
printf("%d\n",count[var[i]]);
}
return 0;
}
void charcount(char *p,int *q)
{
for(;*p;p++)
{
q[*p]++;
}
}
Make sure to compile in C99 or C11 (e.g. gcc -std=c99 file.c
) mode as VLAs are not supported in earlier standards of C.
这篇关于查找字符频率字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!