问题描述:

I tried to write a code that will look for a specific word inside a string and that will count it's place within the string .

If the word doesn't exist inside the string, it should print that the word wasn't found.

For example, for the sentence "I am late" , for "late" the result should be 3.

int count=0,i=0,j=0,k;

char word[30];

getchar();

gets(word);

k=strlen(word);

while(arr[i]!='\0'){

if(arr[i]==word[j]){

i++;

j++;

}

i++;

if(arr[i]==' ') // moves across a word in the string

count++; // count a word the index has passed

}

if(j==k) // if all letters were a match

printf("The word %s is placed in the %d place." , word , count);

else

printf("The word %s is not found." , word);

}

The problem is that for every sentence entered, it prints:

The word %s is not found.

I assumed that it skips for some reason the first part, and goes straight into word is not found, but even after debugging I couldn't catch the moment and reason why it skips.

网友答案:

Note that i++ appears twice in the main loop, once conditionally and once unconditionally. The fact that it appears twice means that when a matching letter is found, i is incremented twice. The intention behind your code could be realized by getting rid of the conditional i++. Making this change and getting rid of the getchar() (which seems pointless from my point of view since it just discards the first letter of the input) and replacing gets by a not-quite-perfect use of fgets yields (with removed lines commented out):

#include <stdio.h>
#include <string.h>

int main(void){
    int count=0,i=0,j=0,k;
    char * arr = "I am late";
    char word[30];
    //getchar();
    fgets(word,30,stdin);
    strtok(word,"\n"); //trick for stripping off newline of nonempty line
    k=strlen(word);
    while(arr[i]!='\0'){
        if(arr[i]==word[j]){
           //i++;
           j++;
        }
        i++;  
        if(arr[i]==' ') // moves across a word in the string
            count++;    // count a word the index has passed
    }

    if(j==k)            // if all letters were a match
        printf("The word %s is placed in the %d place." , word , count);
    else
        printf("The word %s is not found." , word);

    return 0;
}

When I run it and enter late I get the result:

The word late is placed in the 2 place.

Which seems to be almost what you want (there is an off-by-one error if you wanted the number 3). But, don't celebrate too soon since if you run it again with the input mate you get:

The word mate is placed in the 2 place.

Your code (once fixed this way) is really testing if the letters of the input word appear in order in arr, but doesn't check if the letters appear next to each other. You need to rethink your approach.

相关阅读:
Top