gpt4 book ai didi

c - 程序查找文本中有多少个单词不包含特定字符

转载 作者:行者123 更新时间:2023-11-30 16:28:56 24 4
gpt4 key购买 nike

以下程序运行时不会在屏幕上打印任何内容,可能是因为循环遍历了空字符。我不明白为什么会发生这种情况,如何发生,以及如何解决它。

//program to find how many word in the text doesn't contain p char

#include<stdio.h>
#include<stdbool.h>
#define space ' '

void find_word(char s[]) {
bool wordfound = false;

int i, j = 0, word = 0;
i = 0;

while (s[i]) { //s[i]!='\0' does not

if (s[i] != 'p' && s[i + 1] != space) { //for the first word
wordfound = true;
word++;
}

wordfound = false;

if (s[i] == space && s[i + 1] != space) { //for more than one word in the text
for (j = i + 1; s[j] != space; j++)
if (s[j] != 'p' && s[j + 1] != space)
wordfound = true;
}
if (wordfound) {
word++;
}
wordfound = false;
i = j;
i++;
} //end while loop

printf("Number of words not contain p character%d\n\n", word);

}

int main(void) {
char s[] = {"pppp zzzz ppp ssss dfg sfsfdsf"};
find_word(s);
return 0;
}

最佳答案

这段代码有一些问题,但主要的问题是在循环内将j分配给i,这会导致无限循环作为 while(s[i]) 条件永远不会满足。为什么不尝试让它变得简单,就像这样:

//program to find how many word in the text doesn't contain p char

#include<stdio.h>
#include<stdbool.h>
#define space ' '

void find_word(char s[]) {
bool is_in = false;
short words_count = 0, i = 0;

while (s[i]) {
if (s[i] == 'p') { // if this letter is a 'p', mark the word
is_in = true;
}

if (s[i] == space) { // if it's end of word
if (!is_in) { // check if 'p' is present and increase the count
words_count++;
}
is_in = false;
}

i++;
}

if (!is_in) { // check if the last word has 'p'
words_count++;
}

printf("no. of words without p is %d\n", words_count);

}

int main(void) {
char s[] = {"pppp zzzz ppp ssss dfg sfsfdsf"};
find_word(s);
return 0;
}

关于c - 程序查找文本中有多少个单词不包含特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52129023/

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