编写一个C语言程序来计算字符串中单词的总数,并附带示例。
C 语言计算字符串中单词总数的示例 1
此程序允许用户输入一个字符串(或字符数组)和一个字符值。然后,它将使用 For 循环计算此字符串中存在的单词总数。
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, totalwords;
totalwords = 1;
printf("\n Please Enter any String : ");
gets(str);
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
{
totalwords++;
}
}
printf("\n The Total Number of Words in this String %s = %d", str, totalwords);
return 0;
}

在这里,我们使用 For 循环 来迭代字符串中的每一个字符,并查找其中的空格。
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
{
totalwords++;
}
}
str[] = Hello World
第一个 For 循环 – 第一次迭代: for(i = 0; str[i] != ‘\0’ ; i++)
条件为真
if(str[i] == ‘ ‘ || str[i] == ‘\n’ || str[i] == ‘\t’)
=> if(H == ‘ ‘ || H == ‘\n’ || H == ‘\t’) – 条件为假
对剩余的迭代执行相同的操作。如果条件为真(一旦到达 Hello 后的空格),则编译器将执行 totalwords++;
在这种情况下 totalwords = 2(因为它已经是 1 了)
最后,我们使用 C 语言的 printf 语句 来打印字符串中单词的总数。
printf("\n The Total Number of Words in this String %s = %d", str, totalwords);
计算字符串中单词总数的示例 2
此用于计算字符串单词总数的 C 程序与上面的程序相同。在这里,我们只是将 For 循环替换为了 While 循环。我建议您参考 While 循环 来理解循环迭代。
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, totalwords;
totalwords = 1;
i = 0;
printf("\n Please Enter any String : ");
gets(str);
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
{
totalwords++;
}
i++;
}
printf("\n The Total Number of Words in this String %s = %d", str, totalwords);
return 0;
}
Please Enter any String : Tutorial Gateway
The Total Number of Words in this String Tutorial Gateway = 2
计算字符串中单词总数的示例 3
此字符串中的总单词数 程序 与第一个示例相同,但这次我们使用了 函数 的概念来分离逻辑。
#include <stdio.h>
#include <string.h>
int Count_TotalWords(char *str);
int main()
{
char str[100];
int totalwords;
totalwords = 1;
printf("\n Please Enter any String : ");
gets(str);
totalwords = Count_TotalWords(str);
printf("\n The Total Number of Words in this String %s = %d", str, totalwords);
return 0;
}
int Count_TotalWords(char *str)
{
int i, totalwords;
totalwords = 1;
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
{
totalwords++;
}
}
return totalwords;
}
Please Enter any String : Learn c programming with examples
The Total Number of Words in this String Learn c programming with examples = 5
评论已关闭。