下面的 for 循环一直持续到字符串末尾,而 if 分支检查字符“u”在字符串“yuzuf Oztuk”中出现了多少次,即 3 次。同时,变量 count 计算字符串中 u 的数量。当我编译代码时,我得到 15 作为 u 在字符串中出现的次数,这是错误的。
int numTimesAppears(char* mystring, char ch)
{
int i;
int count;
for(i = 0; mystring[i] != '\0' ; ++i)
{
if (mystring[i] == ch)
{
count++;
}
}
return count;
}
最佳答案
I get 15 for the number of times u appears in the string, which is wrong.
关键问题:代码需要初始化
count
的值。 @BLUEPIXY// int count; int count = 0;
极端情况:由于字符串中存在空字符,因此对于任何
numTimesAppears 来说,结果都是 1“字符在字符串中出现的次数” (some_string,'\0')
。do
循环解决了这个问题。类似的标准库函数是strchr()
,它查找第一个匹配项并考虑可搜索字符串的空字符部分: “...终止空字符被视为字符串的一部分。”与所有极端情况一样,可以推断出各种结果 - 最好记录这种情况下的编码目标。i = 0; do { if (mystring[i] == ch) { count++; } } while (mystring[i++]);
由于该函数不会修改检查的字符串,因此将其设置为 const 可以提高函数的适用性,或许还可以提高性能。 @Vlad from Moscow
数组索引最好使用
size_t
而不是int
。int
可能太窄。size_t numTimesAppears(const char* mystring, char ch) { size_t count = 0; size_t i = 0; do { if (mystring[i] == ch) { count++; } } while (mystring[i++]); return count; }
关于C语言中计算某个字符在字符串中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46085187/