简体   繁体   English

使用 strchr() 计算字符串中某个字符的出现次数

[英]Using strchr() to count occurrences of a character in a string

I'm almost finished with the class semester, and I'm working on an assignment to write a function to find the number of a certain character in a string, given the function prototype the teacher assigned.我的课堂学期快结束了,我正在做一项作业,根据老师分配的函数原型,编写一个函数来查找字符串中某个字符的编号。 I know I must be doing something stupid, but this code is either locking up or looping indefinitely in my function.我知道我一定在做一些愚蠢的事情,但是这段代码在我的函数中要么锁定要么无限循环。

It is an assignment, so I'm not looking for anyone to do my homework for me, but merely to point out where I'm wrong and why, so I can understand how to fix it.这是一项任务,所以我不是在寻找任何人为我做作业,而只是指出我错在哪里以及为什么,这样我就可以了解如何解决它。 I would appreciate any help that you are willing to give.如果您愿意提供任何帮助,我将不胜感激。

Here's the code I've written:这是我写的代码:

#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

Your loop is always looking from the beginning of pString , and is always finding the first 'e' over and over again.您的循环总是从pString的开头开始寻找,并且总是一遍又一遍地找到第一个 'e'。

If you declare char* pTemp = pString;如果你声明char* pTemp = pString; then you can iterate a little differently (I pasted the wrong version earlier, sorry!):然后你可以稍微不同地迭代(我之前粘贴了错误的版本,抱歉!):

char* pTemp = pString;

while(pTemp != NULL)                                                                                                    
{                                                                                                                       
    pTemp = strchr(pTemp, c);                                                                                                           
    if( pTemp ) {
        pTemp++;
        count++;
    }                                                                                                
}

This forces pTemp to point just after the character you just found before looking for the next one.这会强制pTemp在查找下一个字符之前指向您刚刚找到的字符。

It would be easier to just do:这样做会更容易:

char* pTemp = pString;
while( *pTemp )
    if( *pTemp++ == c) count++;

Okay, after thinking about it, even after you already have this working, I changed the inner loop to a form I am more happy with:好吧,仔细想想,即使你已经有了这个工作,我还是把内循环改成了我更满意的形式:

while( (pTemp = strchr(pTemp, c)) != NULL) {                                                                                                                       
   count++;                                                                                                             
   pTemp++;
}

You are always restarting from the beginning.你总是从头开始。 No wonder you never come to an end.难怪你永远不会走到尽头。

char* pTemp; // Init here = pString
do {
    pTemp = strchr(pString, c); // pString? Really? Should be pTemp
    count++;
} while(pTemp != NULL); // pTemp != NULL is verbose for pTemp here

Still, better avoid the library function and do a direct loop over all elelemts.不过,最好避免使用库函数并在所有元素上进行直接循环。

Just to jump on the wagon train:只是为了跳上马车:

size_t count(const char* s, char c) {
    size_t r = 0;
    for (; *s; ++s)
        r += *s == c;
    return r;
}

If you insist on using strchr() :如果您坚持使用strchr()

size_t count(const char* s, char c) {
    size_t r = 0;
    while ((s = strchr(s, c)))
        ++r;
    return r;
}

strchr() is always looking in the same place, it will not progress through the string... strchr()总是在同一个地方寻找,它不会在字符串中前进......

Try this modification to traverse through the string using length of string, and a simple char comparison:尝试使用字符串长度和简单的char比较来遍历字符串:

int i, len = strlen(pString);
count = 0;
for(i=0;i<len;i++)
{
    if(pString[i] == c) count++; //increment count only if c found
}

return count;  

Without using strlen() (to address comment)不使用strlen() (解决评论)

i=-1, count = 0;
while(pString[++i])
{
   if(pString[i] == c) count++;
}  
return count;

strchr returns a pointer to the first occurrence of the character c in pString. strchr 返回一个指向字符 c 在 pString 中第一次出现的指针。

So if you give a pointer to the beginning of your string in each loop, pTemp will always have the same value and never be NULL if the character c exists.因此,如果您在每个循环中提供指向字符串开头的指针,则 pTemp 将始终具有相同的值,并且如果字符 c 存在,则永远不会为 NULL。 That's why you have an infinite loop.这就是为什么你有一个无限循环。

You might want to do some pointer arithmetic to solve your problem here ;)您可能想在这里进行一些指针运算来解决您的问题;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM