gpt4 book ai didi

c - 字计数器代码跳过

转载 作者:行者123 更新时间:2023-11-30 15:02:17 24 4
gpt4 key购买 nike

我尝试编写一个代码来查找字符串中的特定单词,并计算它在字符串中的位置。如果字符串中不存在该单词,则应打印出未找到该单词。例如,对于句子“我迟到了”,“迟到”的结果应该是 3。

int count=0,i=0,j=0,k;
char word[30];
getchar();
gets(word);
k=strlen(word);
while(arr[i]!='\0'){
if(arr[i]==word[j]){
i++;
j++;
}
i++;
if(arr[i]==' ') // moves across a word in the string
count++; // count a word the index has passed
}
if(j==k) // if all letters were a match
printf("The word %s is placed in the %d place." , word , count);
else
printf("The word %s is not found." , word);
}

问题是对于输入的每个句子,它都会打印:

The word %s is not found.

我认为它由于某种原因跳过了第一部分,并直接进入找不到单词,但即使在调试之后我也无法捕获它跳过的时刻和原因。

最佳答案

请注意,i++ 在主循环中出现两次,一次有条件,一次无条件。它出现两次的事实意味着当找到匹配的字母时,i 会增加两次。通过删除条件 i++ 可以实现代码背后的意图。进行此更改并摆脱 getchar() (从我的角度来看,这似乎毫无意义,因为它只是丢弃输入的第一个字母)并将 gets 替换为不太完美地使用 fgets 产量(删除的行被注释掉):

#include <stdio.h>
#include <string.h>

int main(void){
int count=0,i=0,j=0,k;
char * arr = "I am late";
char word[30];
//getchar();
fgets(word,30,stdin);
strtok(word,"\n"); //trick for stripping off newline of nonempty line
k=strlen(word);
while(arr[i]!='\0'){
if(arr[i]==word[j]){
//i++;
j++;
}
i++;
if(arr[i]==' ') // moves across a word in the string
count++; // count a word the index has passed
}

if(j==k) // if all letters were a match
printf("The word %s is placed in the %d place." , word , count);
else
printf("The word %s is not found." , word);

return 0;
}

当我运行它并输入late时,我得到结果:

The word late is placed in the 2 place.

这似乎几乎就是您想要的(如果您想要数字 3,则会出现差一错误)。但是,不要庆祝得太早,因为如果您使用输入 mate 再次运行它,您会得到:

The word mate is placed in the 2 place.

您的代码(一旦以这种方式修复)实际上是在测试输入单词的字母是否按顺序出现在 arr 中,但不会检查字母是否彼此相邻出现。您需要重新考虑您的方法。

关于c - 字计数器代码跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41105911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com