这是一个查找字符串中字符数的程序。但它计算错误的字符数。它也计算白色空间吗?即使这是真的,总数是多少? (见下面的输出)
#include <stdio.h>
#include <conio.h>
void occurrence(char str[100], char ch)
{
int count=0,max =0,i;
for(i=0;i<=100;i++)
{
if(str[i]!='\0')
{
max = max + 1;
if(str[i]==ch)
{
count = count + 1;
}
}
}
printf("\nTotal Number of characters : %d\n",max);
printf("\nNumber of Occurrences of %c : %d\n",ch,count);
}
int main(void)
{
void occurrence(char [], char);
int chk;
char str[100], ch, buffer;
clrscr();
printf("Enter a string : \n");
gets(str);
printf("Do you want to find the number of occurences \nof a particular character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
do
{
if (chk==1)
{
buffer = getchar(); //dummy varaiable to catch input \n
printf("Enter a Character : ");
ch = getchar();
occurrence(str,ch);
printf("\n\nDo you want to check the number of occurences \nof another character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
}
else
{
exit();
}
}
while(chk);
return 0;
}
答案 0 :(得分:2)
计算字符的for
循环有两个重要的错误:
从0到100,它应该从0到99.如果你分配100个元素的数组,那么最高元素的索引是99,总共有100个元素。传统上,循环的退出条件是i < 100
,而不是i <= 100
。
找到'\ 0'后继续前进。 '\ 0'字符标记字符串的结尾,您不应该计算其后的任何字符。 '\ 0'之后的一些字符本身可能是'\ 0',所以你不会计算它们;但那里可能还有其他任何类型的垃圾,这些都会搞砸你的数量。您必须弄清楚如何在找到'\ 0'字符后立即将for
循环更改为退出,并且在该点之后不计算任何其他内容。
答案 1 :(得分:0)
是的,空白是一个角色。也是数组中100个元素的字符。你正在计算除零之外的所有内容,sp我想你有11个空值。此外,你的for循环还是一个。
答案 2 :(得分:0)
这将为您提供正确的输出。
void occurrence(char str[100], char ch)
{ int count = 0,max = 0,i = 0;
while(str[i]!='\0')
{
max = max + 1;
if( str[i] == ch )
{
count = count + 1;
}
i++;
}
}