c中的字计数器不起作用

nam*_*mco 1 c string pointers

我有如下代码.
我想计算用分隔符分隔的文本中的单词数.
代码编译但停止.
问题是什么?
这是我的代码.

#include <stdio.h>
#include <string.h>

int WordCount(char *text,char delimiter)
{
    char *s;
    int count = 0;
    strcpy(s,text);
    while(*s){
        if(*s==delimiter){
            count++;
        }
    }
    return count;
}

int main(void)
{
    char *line = "a,b,c,d,e";

    printf("%d\n",WordCount(line,','));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*her 5

你忘了增加指针s,因此你有一个无限循环,而不是复制字符串(你需要为其分配内存),只需让它指向输入.

int WordCount(char *text,char delimiter)
{
    char *s = text;
    int count = 0;
    // strcpy(s,text);
    while(*s){
        if(*s==delimiter){
            count++;
        }
        ++s;
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)