如何在C中显示字符串中的单词及其出现次数
基本上,我希望在字符串中显示单词及其出现次数。它可以区分大小写,反之亦然 例如,如果输入字符串为“如何在C中显示字符串中的单词及其出现次数,c,word,case-sensitive,c-strings,find-occurrences,C,Word,Case Sensitive,C Strings,Find Occurrences,基本上,我希望在字符串中显示单词及其出现次数。它可以区分大小写,反之亦然 例如,如果输入字符串为“Hello World How are you Hello How”,则输出应为: Hello,2 World,1 How,2 are,1 you,1 我还不知道这其中的逻辑;有什么帮助吗?使用 检查这三个API。找出要编写、实现、遇到问题的代码,然后回来,我们将在这里提供帮助。\include #include <stdio.h> #include <string.h&g
Hello World How are you Hello How
”,则输出应为:
Hello,2
World,1
How,2
are,1
you,1
我还不知道这其中的逻辑;有什么帮助吗?使用
检查这三个API。找出要编写、实现、遇到问题的代码,然后回来,我们将在这里提供帮助。\include
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
bool eq(const char *s, const char *w, char ignore_case){
char si, wi;
while(*w && !isspace(*w)){
if(ignore_case != 'n'){
si = tolower(*s++);
wi = tolower(*w++);
} else {
si = *s++;
wi = *w++;
}
if(si != wi)
return false;
}
return !*s || isspace(*s);
}
char *next_word(char *w){
while(*w && !isspace(*w))
++w;
if(!*w)
return w;
while(isspace(*w))
++w;
return w;
}
int main() {
char ignore_case = 'n';
char *word, *str;
char string[128];
printf("ignore case ?(y/n):");
scanf("%c", &ignore_case);
printf("input string : ");
scanf(" %127[^\n]", string);
str = string;
while(*str){
int counter = 1;
word = next_word(str);//skip first word
while(*word){
char *p = NULL;
if(eq(str, word, ignore_case)){
p = word;
++counter;
}
word = next_word(word);//move to next word top
if(p)
memset(p, ' ', word - p);//clear already match word
}
word = str;
str = next_word(str);
while(*word && !isspace(*word))
putchar(*word++);
printf(",%d\n", counter);
}
return 0;
}
#包括
#包括
#包括
布尔均衡(常量字符*s,常量字符*w,字符忽略大小写){
char-si,wi;
while(*w&!isspace(*w)){
如果(忽略大小写!=“n”){
si=tolower(*s++);
wi=tolower(*w++);
}否则{
si=*s++;
wi=*w++;
}
if(si!=wi)
返回false;
}
返回!*s | | isspace(*s);
}
char*下一个单词(char*w){
while(*w&!isspace(*w))
++w;
如果(!*w)
返回w;
while(isspace(*w))
++w;
返回w;
}
int main(){
char ignore_case='n';
字符*word,*str;
字符串[128];
printf(“忽略案例”(是/否):”;
scanf(“%c”,忽略大小写(&U);
printf(“输入字符串:”);
scanf(“%127[^\n]”,字符串);
str=字符串;
while(*str){
int计数器=1;
word=下一个单词(str);//跳过第一个单词
while(*字){
char*p=NULL;
if(eq(str,word,忽略大小写)){
p=单词;
++计数器;
}
word=下一个单词(word);//移动到下一个单词顶部
如果(p)
memset(p',,word-p);//清除已匹配的单词
}
word=str;
str=下一个单词(str);
while(*word&&!isspace(*word))
putchar(*word++);
printf(“,%d\n”,计数器);
}
返回0;
}
手动尝试,算法将出现。。。