c - 如何计算单词出现在短语中的次数
问题描述
我正在尝试创建一个代码,其中我必须计算一个单词在句子中出现的次数,但是经过大量搜索和搜索,我只能找到使用该fgets
函数的代码,我想知道是否你会知道其他什么东西,我可以替换fgets
并仍然工作整个事情。
这是我现在开发的代码:
#include <stdio.h>
int
main()
{
char phrase[250];
char word[50], c;
int count;
int a;
count = 0;
printf("Type a phrase: ");
scanf("%[^\n]", &phrase);
printf("Type a word: ");
scanf("%s", &word);
for (a = 0; word[a] != '\0'; a++) {
if (word[a] == c)
count++;
}
if (count == 0) {
printf("word not found in the sentence");
}
else {
printf("Count: = %d\n", count);
}
return 0;
}
除了一切,我相信我在 for 中做错了什么,但我无法理解。如果你能帮助我理解我的错误,以及除了可以使用的其他东西fgets
,我很乐意。
解决方案
我不明白你的for
循环和if
陈述。我没有测试这段代码。但它的逻辑可能会有所帮助:
int j = 0;
int counter = 0;
for(int i = 0; phrase[i] != '\0'; i++)
{
if (word[j] = phrase[i])
{
j += 1;
if (word[j] == '\0')
{
counter += 1;
j = 0;
}
}
else
{
j = 0;
}
}
推荐阅读
- c - 加法持久性和加法根程序在输入数字后无响应
- sql - 错误:函数round(双精度,整数)不存在
- auth0 - Appsync:使用 auth0 时在 context.identity 中获取用户信息
- java - 我的 JSP 连接到 MySql DB 但不会列出项目
- html - 我无法在 html 中为此布局创建列,请告诉我我该怎么做
- sql-server - 覆盖 T-SQL 脚本中的 SQLCMD 变量
- azure - 在 azure 函数中从 iothub 获取 deviceId
- c# - Outlook VSTO - 检索会议组织者
- regex - 放入 if 子句时,负正则表达式环视如何工作?
- sql - SQL Server 在没有循环或游标的情况下获取关系表中的所有组合