![](/img/trans.png)
[英]Make a function that shows how many times a word occurs in a string/sentence
[英]How to find number of times that a given word occurs in a sentence [C code]?
這是我的代碼。 我需要找出給定單詞(短字符串)在句子(長字符串)中出現的次數。 樣本輸入:貓坐在墊子上樣本輸出:2由於某種原因,字符串比較功能不起作用,我的輸出為零。 請忽略代碼中的注釋,因為它們已用於調試代碼。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char word[50];
gets(word);
int len = strlen(word);
//printf("%d",len);
char nword[len];
char s[100];
strcpy(nword,word);
puts(nword);
printf("\n");
gets(s);
//printf("%d",strlen(s));
char a[50][50];
int i,j,k;
j = 0;
for(i=0;i<strlen(s);i++)
{
a[i][j] = s[i];
printf("%c",a[i][j]);
if(s[i] == ' ')
{
j++;
printf("\n");
}
}
printf("%d",j);
k = j;
//printf("\nk assigned\n");
j = 0;
//printf("j equal to zero\n");
int count = 0;
int temp = 0;
//printf("count initialized.\n");
for(i=0;i<k;i++)
{
if(strcmp(a[i],nword) == 0)
count++;
}
printf("\n%d",count);
return 0;
}
您的主要問題是由於許多原因導致此循環
int i,j,k;
j = 0;
for(i=0;i<strlen(s);i++)
{
a[i][j] = s[i];
printf("%c",a[i][j]);
if(s[i] == ' ')
{
j++;
printf("\n");
}
}
首先,你有你的指數為倒退- a[i][j]
表示第i個串和第j個字符,但因為你是遞增j
每個字你想要它周圍的其他方式- a[j][i]
。
其次,您不能同時使用i
來索引s
和a
。 考慮一下在構建第二個字符串時會發生什么。 在您的示例輸入中,第二個單詞在i
為4時開始,因此第一個字符將存儲為a[1][4]=s[4]
,從而使a[1][0]
到a[1][3]
未被初始化。 因此,您必須使用第3個變量來跟蹤您在另一個字符串中的位置。
碰到空格時,您不想將其添加到單詞中,因為以后將不匹配。 您還需要在每個字符串的末尾添加一個空終止符,否則您的代碼將不知道字符串的末尾在哪里。
將以上內容放在一起可以得到如下所示的內容:
int i,j,k;
k = j = 0;
for(i=0;i<strlen(s);i++)
{
if(s[i] == ' ')
{
a[j][k] = '\0';
j++;
k=0;
printf("\n");
}
else
{
a[j][k] = s[i];
printf("%c",a[j][k]);
k++;
}
}
a[j][k]='\0';
問題是a
是一個二維數組,您將其引用為一維數組。 Maby您使用2維數組來表示i = line,j = character。 如果您保留此想法,則必須這樣做:
j=0;
for(i=0;i<k;i++)
{
if(strcmp(a[i][j],nword) == 0)
count++;
j++;
}
但是,隨后將很難檢測到被分成兩半的單詞。 我建議將a
保持為一維數組。 串行復制s[i]
的內容,當您想區分行時,請使用\\r\\n
運算符。
我認為您使用二維數組是錯誤的。 a[0][j]
應該是s[i]
的第一個單詞。 但是你在做什么是a[i][0] = s[i]
,對我來說這沒有意義。
最好的祝福
我將使用功能strtok()
和strcmp()
實現此目的:
int main(void)
{
char word[] = "the"; /* the word you want to count*/
char sample[] = "the cat sat on the mat"; /* the string in which you want to count*/
char delimiters[] = " ,;.";
int counter;
char* currentWordPtr;
/* tokenize the string */
currentWordPtr = strtok(sample, delimiters);
while(currentWordPtr != NULL)
{
if(strcmp(word, currentWordPtr) == 0)
{
counter++;
}
/* get the next token (word) */
currentWordPtr = strtok(NULL, delimiters);
}
printf("Number of occurences of \"%s\" is %i\n", word, counter);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.