为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题
在这个 C 语言程序中,我们需要统计一个给定字符串中某个单词出现的次数。在这里,我们需要找出单词“the”在一个字符串中出现的次数。为此,我们检查每个单词是否以字母“t”开头;如果是,则检查“t”之后的两个字母是否是“h”和“e”,并且后面是否跟着一个空格;如果所有条件都满足,则将计数器加一。最后,我们将输出计数器数字。在此程序中,使用了“while 循环”进行执行。
while (testExpression)
{
// codes inside the body of a while
}
这里“while 循环”评估测试表达式。如果测试表达式为真,则执行“while 循环”内的代码。此过程一直持续到测试表达式为假;如果测试表达式为假,则“while 循环”终止。
步骤 1: 包含头文件以使用 C 程序中的内置函数。
步骤 2: 声明整数变量“count, times, t, h, e, space”,并设置 count=0, times=0。
步骤 3: 声明字符数组“str”。
步骤 4: 使用 gets() 函数从用户读取字符串。
步骤 5: 使用带条件 str[count]!='\0' 的 while 循环,将 count 递增 1。
步骤 6: 赋值 i=0。
步骤 7: 使用另一个带条件“i<=count-3”的 for 循环执行步骤 8。
步骤 8: 检查 str[i]=t 或 str[i]=T,如果为真,则变量 't' 变为 1。
步骤 9: 检查 str[i+1]=h 或 str[i+1]=H,如果为真,则变量 h 变为 1。
步骤 10: 检查 str[i+2]=e 或 str[i+2]=E,如果为真,则变量 E 变为 1。
步骤 11: 检查 str[i+3]=' ' 或 str[i+3]='\0',如果为真,则变量 space 变为 1。
步骤 12: 检查“t”和“h”和“e”和 space 是否都为 1,如果是,则将变量 times 递增 1。
步骤 13: 将 'i' 递增 1,并重复步骤 7。
步骤 14: 然后,显示单词“the”在句子中出现的频率(即 times 的值)。
#include<stdio.h>
#include<string.h>
void main() {
int count = 0, i, times = 0, t, h, e, space;
char str[100];
puts("Enter a string:");
gets(str);
while (str[count] != '\0') {
count++;
} /*Finding number of times word 'the'*is coming in the sentence*/
for (i = 0; i <= count - 3; i++) {
t = (str[i] == 't' || str[i] == 'T');
h = (str[i + 1] == 'h' || str[i + 1] == 'H'); /* Checks the word "the" is present in the sentence that user enters */
e = (str[i + 2] == 'e' || str[i + 2] == 'E');
space = (str[i + 3] == ' ' || str[i + 3] == '\0');
if ((t && h && e && space) == 1)
times++;
}
printf("Frequency of the word \'the\' is %d\n", times); /* displays output of the program */
}
Enter a string: The Teacher's day is the birth day of Dr.S.Radhakrishnan Frequency of the word 'the' is 2