【发布时间】:2014-06-10 07:24:29
【问题描述】:
我的学期快结束了,我正在写一个函数来查找字符串中某个字符的编号,给定老师分配的函数原型。我知道我一定是在做一些愚蠢的事情,但是这段代码要么被锁定,要么在我的函数中无限循环。
这是一项任务,所以我不是在寻找任何人为我做作业,而只是指出我错在哪里以及原因,以便我了解如何解决它。如果您愿意提供任何帮助,我将不胜感激。
这是我写的代码:
#include <stdio.h>
#include <string.h>
int charCounter(char* pString, char c);
int main(void)
{
char* inpString = "Thequickbrownfoxjumpedoverthelazydog.";
int charToCount;
int eCount;
eCount = 0;
charToCount = 'e';
eCount = charCounter(inpString, charToCount);
printf("\nThe letter %c was found %d times.", charToCount, eCount);
return 0;
} // end main
int charCounter(char* pString, char c)
{
int count = 0;
char* pTemp;
do
{
pTemp = strchr(pString, c);
count++;
}
while(pTemp != NULL);
return count;
} // end countCharacter
【问题讨论】:
-
必须使用
strchr吗?我会对所有元素进行直接迭代。 -
现在把它改成 strchr(pTemp, c) 你一直从原始字符串的开头开始
-
考虑使用
const-正确性:虽然由于历史原因,C 字符串文字属于char[]类型,但它们实际上是不可变的。 -
你只需要热爱那些教育作业...
-
他们是有教育意义的。
标签: c string count character strchr