字符串中出现的次数

时间:2016-04-15 16:29:24

标签: c arrays

给定一个数组字符串,我必须输入一个单词并在字符串中找到该单词的出现位置,但是我无法输入我需要找到该单词的单词。我不能使用指针,因为它没有被教学大纲所涵盖。帮助将不胜感激

#include <stdio.h>
#include <strings.h>
int main()
{
    char sentence[100],word[20],temp[20];
    int i=0,j=0,occurrences=0;
    scanf("%[ ^\n]s",sentence);
    printf("Enter the word to be searched:\n");
    fgets(word,20,stdin);
    while(sentence[i]!='\0')
    {
        while(sentence[i]!=' '&&sentence[i]!='\0')
        {
            temp[j++]=sentence[i];
            i++;
        }
        temp[j]='\0';

        if((strcmp(temp,word))==0)
        occurrences++;

        if(sentence[i]==' ')
        j=0;
    }
    printf("Number of Occurrences of the word are %d",occurrences);
    return 0;
}

2 个答案:

答案 0 :(得分:1)

  • 标题的名称为string.h而不是strings.h
  • 使用scanf(" %s",word);代替fgets(word,20,stdin);进入 word。查看%s之前的空格以消耗空格。
  • 此外,您必须在代码中i++之后添加j=0,这就是原因 无限地奔跑。

你的代码应该是这样的:

#include <stdio.h>
#include <string.h> //fix 1
int main()
{
    char sentence[100],word[20],temp[20];
    int i=0,j=0,occurrences=0;
    scanf("%[^\n]s",sentence);
    printf("Enter the word to be searched:\n");
    scanf(" %s",word); //fix 2
    while(sentence[i]!='\0')
    {
        while(sentence[i]!=' '&&sentence[i]!='\0')
        {
            temp[j++]=sentence[i];
            i++;
        }
        temp[j]='\0';

        if((strcmp(temp,word))==0)
        occurrences++;
        if(sentence[i]==' ')
        {
            j=0;i++; //fix 3
        }
    }
    printf("Number of Occurrences of the word are %d",occurrences);
    return 0;
}

答案 1 :(得分:0)

  1. #include <strings.h>更改为#include <string.h>

  2. scanf("%[ ^\n]s", sentence);无法按预期运行。要输入包含空格字符的字符串,您应该使用fgets(word, 20, stdin);。不要忘记处理'\ n'。

  3. 删除word中的'\ n'。

  4. 顺便说一句,以下代码对我来说更清楚:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char sentence[100], word[20];
        int occurrences = 0, i = 0;
        fgets(sentence, 100, stdin);
        sentence[strcspn(sentence, "\n")] = '\0';
        printf("Enter the word to be searched:\n");
        fgets(word, 20, stdin);
        word[strcspn(word, "\n")] = '\0';
        while(strlen(word) + i <= strlen(sentence))
        {
            if(memcmp(word, sentence + i, strlen(word) - 1) == 0)
                occurrences++;
            i++;
        }
        printf("Number of Occurrences of the word are %d", occurrences);
        return 0;
    }
    
相关问题