Home > Enterprise >  Count the Occurrences of a Substring in String
Count the Occurrences of a Substring in String

Time:01-04

My program is supposed to count in a string an entered string.

For example:

Enter a text: Hello World
Enter a string: llo
occurs 1 times in Hello World

Unfortunately, my program does not give me anything. Does anyone have a tip for me?

void aufgabe7(char string[MAX], char stringw[MAX]){
    printf("Enter a Text: \n");
    fgets(string, MAX, stdin);
    int i, j, len, len2;
    int count = 0;
    int count2 = 0;
    len = strlen(string);
    
    printf("Enter a string: \n");
    fgets(stringw, MAX, stdin);
    len2 = strlen(stringw);

    for (i = 0; i < len;)
    {
        j = 0;
        count = 0;
        while ((string[i] == stringw[j]))
        {
            count  ;
            i  ;
            j  ;
        }
        if (count == len2)
        {
            count2  ;
            count = 0;
        }
        else
            i  ;
        
        
    }
    
    printf("%s occurs %d times in %s \n", stringw, count2, string);
    
}

void main (void){

    char data[MAX];
    task7(&data[0], &data[0]);

}

CodePudding user response:

As commenter @Steve Summit noted, you are searching for a string read from fgets, which has a trailing newline. Normally, you would need to remove the newline from the input from fgets, otherwise it is part of the searched for string. The simplest way to do this is to call buffer[strcspn(buffer, "\n")] = '\0'; as documented in this question.

However, I feel the correct answer to this question is that there is a more idiomatic way of doing this with C than comparing char by char: using strstr with pointer arithmetic will work just as well and is cleaner to read:

char input[SIZE];
char search[SIZE];
size_t count = 0;

printf("Enter a phrase: ");
fgets(input, SIZE, stdin);
input[strcspn(input, "\n")] = '\0'; 
printf("\nEnter a sub-phrase: ");
fgets(search, SIZE, stdin);
search[strcspn(search, "\n")] = '\0';
char *p = input;
while((p = strstr(p, search)) != NULL)
{
    printf("Found occurrence of '%s' at position %td\n", search, (ptrdiff_t)(p - input));
    count  ;
    p  ;
}

printf("Found %zu occurrences of '%s'.\n", count, search);
  • Related