我需要在C中的单词列表中搜索单词,并计算该单词的出现次数。
这是我到目前为止所尝试的内容:
{
char *namePtr , *newnamePtr ; char newname[1][8] ;
int occurrence ;
namePtr=&name[i];
printf("enter the word you want to count : \n");
scanf("%s",newname[1][8]);
for(i=0; i< N ; i++)
{
if(strcmp(namePtr,newnamePtr)==0)
occurrence++ ;
else
if(strcmp(namePtr,newnamePtr)!=0)
printf("this word does not exist in the list!");
}
printf("the occurrence of this word is %d",occurrence) ;
}
如何计算单词列表中单词的出现次数?
答案 0 :(得分:1)
如果您想要计算子字符串,可以使用以下代码:
int main(void)
{
char text[] = "foo bar foo bar foo";
char word[] = "foo";
char *p;
int occurences = 0;
for (p = text; (p = strstr(p, word)) != NULL; p += sizeof(word) - 1)
{
occurences++;
}
printf("Occurences of %s = %d\n", word, occurrences);
}
答案 1 :(得分:0)
要搜索由分隔符分隔的句子/单词列表中的单词,您可以使用strstr()和循环来查找该单词的所有匹配项。
样本可能是这样的。
//strstr returns a pointer to first occurrence of the string found else NULL
do
{
p=strstr(str1,str2);
if(p) count++;
}while(p);
还有一个several other algorithms来实现同样的目标。
答案 2 :(得分:0)
#include <stdio.h>
#include <string.h>
#define N 10
char *name[N] = {
"the", "name", "pointer", "the", "count",
"word", "want", "to", "count", "exist"
};
int main(){
char *namePtr , *newnamePtr ;
char newname[8];
int i, occurrence = 0;
printf("enter the word you want to count : \n");
scanf("%s", newname);
newnamePtr = newname;
for(i=0; i< N ; i++){
namePtr = name[i];
if(strcmp(namePtr, newnamePtr)==0)//strcmp(name[i], newname)
occurrence++;
}
if(occurrence==0)
printf("this word does not exist in the list!");
else
printf("the occurrence of this word is %d", occurrence);
return 0;
}
答案 3 :(得分:-1)
这是一个简化版本:
char newname[80];
int occurrence = 0;
printf("enter the word you want to count : \n");
scanf("%s", newname);
for (i = 0; i < N ; ++i)
{
if( strcmp(name[i], newname) == 0 ) // access list directly
++occurrence;
else // no need to check the inverse of the condition
printf("this word does not exist in the list!");
}
printf("the occurrence of this word is %d", occurrence) ;
要计算子字符串(部分匹配),请替换:
if( strcmp(name[i], newname) == 0 ) // access list directly
带
if( strstr(name[i], newname) != NULL ) // access list directly