Search code examples
cloopssubstringc-stringsfunction-definition

C Program returns unexpected output


This code is supposed to determine if a word is present in a sentence or not. I tried with the input sen:"my name is", search:"name", but it displays not found. Please help me. Thanks!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
bool s(char *sen, char *search) {
    int k=1, i=0;
    while (*sen!='\0') {
        if (k==1 || *(sen-1)==' ') {
            if (*sen==search[i]) {
                i++;
                if (i==strlen(search) && (*(sen+1)==' ' || *(sen+1)=='\0')) return true;
            }
            else i=0;
        }
        k=0;
        sen++;
    }
    return false;
}
void main() {
    char sen[100], search[20];
    fgets(sen, 100, stdin);
    scanf("%s", search);
    if (s(sen, search)) printf("Found");
    else printf("Not found");
}

Solution

  • take a closer look at: if (k==1 || *(sen-1)==' ') { i'm thinking this is supposed to check for the beginning of a word right ? if the check ever fails this will only be true once. For the beginning of the word try this instead:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdbool.h>
    bool s(char *sen, char *search) {
        int k=1, i=0;
        while (*sen!='\0') {
            if (k==1 || *(sen-1)==' ') { 
               if (*sen==search[i]) {
                    k = 1;
                    i++;
                    if (i==strlen(search) && (*(sen+1)==' ' || *(sen+1)=='\0' || *(sen+1)=='\n')) return true;
                }
                else{ 
                   i=0;
                   k=0;
                }
            }
            sen++;
        }
        return false;
    }
    void main() {
        char sen[100], search[20];
        fgets(sen, 100, stdin);
        scanf("%s", search);
        if (s(sen, search)) printf("Found");
        else printf("Not found");
    }
    

    k will now only be set to 0 if the beginning doesn't match, and after the beginning was matched it will be set to 1. I'm assuming that's what k was for here.

    Also, your first String is "terminated" using the Enter key, so they last Symbol will not be a '\0' but a '\n' for the new line operation: if (i==strlen(search) && (*(sen+1)==' ' || *(sen+1)=='\0' || *(sen+1)=='\n')) return true;