count_word 函数在 C 中返回 0

标签 c counter

这是我关于堆栈溢出的第一篇文章:) 尽管有很多关于“计算字数”的帖子,但我没有找到与我的问题相关的帖子。

我 2 周前开始学习 C。我必须返回字符串中的单词数,这是我目前正在做的一个更大练习的一部分。我不明白为什么它不起作用,我在这里恳请一些提示。

ft_strlen(char *str) //counting nb of char in the string
{
    int     size;

    size = 0;
    while (str[size])
        size++;
    return (size);
}

int     ft_word_count(char *str)
{
    int     i;
    int     size;
    int count_word;

    i = 0;
    size = ft_strlen(str);
    count_word = 0;
    while (str[i] < size - 1) //counting nb of words in the string, I added "-1" to size to get rid of the '\0'
    {
        if (i <= 32 || i > 126 ) //defining what will make a word
            count_word++;
        i++;
    }
    return (count_word);
}

int     main(void)
{
    char    str[]="Meine Frau liebt grosse Pferde";

    ft_strlen(str);
    printf("%d", ft_word_count(str));
    return (0);
}

它返回 0 而不是 5,奇怪,不明白为什么。 如果我只使用我的 strlen,它会按预期返回“30”。所以 ft_word_count 有问题

用 gcc 编译。 语法不简洁,但这是我学校要求的规范的一部分。

感谢您的参与

查尔斯

最佳答案

你应该忽略多个空格才能正确计数

i=0;
count_word=0;

while(str[i]>0)
{
  if((str[i]!= ' '))
  {

     if(!toggle && str[i]!= ' ')
        count_word++;
     toggle=1;
  }
  else
    toggle=0;
  i++;
}

关于count_word 函数在 C 中返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46231286/

相关文章:

c - 传递数组作为参数

c++ - main() 在 C/C++ 中有多少个参数

比较分数与结构

python - 如何计算快速排序中的交换? (Python)

Javascript 将函数的输出保存到站点?

c++ - 警告 : comparison of distinct pointer types

c++ - c/c++ 中什么是类型安全的

Python:计算一列中单词的频率并将结果存储到数据框的另一列中

javascript - 使用 Javascript、HTML 和 CSS 的计数器不起作用