【发布时间】:2017-09-15 03:34:33
【问题描述】:
这是我关于堆栈溢出的第一篇文章 :) 尽管有很多关于“计数单词”的帖子,但我没有找到与我的问题相关的帖子。
我在 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 编译。 语法并不简洁,但这是我学校要求的规范的一部分。
感谢您的意见
查尔斯
【问题讨论】:
-
if (i <= 32 || i > 126 ) count_word++;:i是索引,而不是字符代码。 -
1)
while (str[i] < size - 1)-->while (i <= size) -
2)
if (i <= 32 || i > 126 )-->if (str[i] <= ' ' || (unsigned char)str[i] > '~' )? -
是的 :) 就是这样 :)。它返回 4 而不是 5 但我只需要根据我的情况工作。感谢您的帮助
-
如果
i < size-1,你会得到4。使用i <= size代替它。