0

I need to make a function that receives a substring as an argument and checks if any of the strings in a linked list contain that substring.

The function creates a new linked list with all of the strings that contain the substring given.

The function looks like this:

    lista *lista_pesquisa_substring(lista *lst, char *substring)
{
    l_elemento *aux, *curr;
    lista *lis2;
    int i = 0, tamanho;
    lis2 = lista_nova();
    if(lst == NULL || substring == NULL){
            return NULL;
    }
    for (aux = lst->inicio; aux != NULL; aux = aux->proximo)
            {
                curr = lista_elemento(lis2, i);
                if (strstr(*aux->str, substring) != NULL)
                {
                    lista_insere(lis2, aux->str, curr);
                    i++;
                }
            }
            tamanho = lista_tamanho(lis2);
            printf("Foram carregados %d jogos.\n", tamanho);
            for(i = 0; i < tamanho; i++)
            {
                curr = lista_elemento(lis2, i);
                printf("Pos %d -> %s\n", i, curr->str);
            }
            return lis2;
        }

The if statement isn't working as intended. It only works if the substring given is exactly the same as a string from the linked list.

For example, if a string from the linked list is "Hello there" and the substring given is "Hello there", the if statement works. But if the substring is "there", the if doesn't work.

EDIT: I should also mention that the substring used as an argument is wrote by the user using the fgets function.

I have tried to use a pre-existing string instead to test it and it works. So I'm confused as to why it doesn't work with a string that's input by the user.

Herbert
  • 3
  • 3

1 Answers1

0

I should also mention that the substring used as an argument is wrote by the user using the fgets function.....
So I'm confused as to why it doesn't work with a string that's input by the user.

One possible reason that it doesn't work when you take input from user using fgets() function is that when user give input and press ENTER key, fgets() consider the newline character as a valid character and includes it in the input string given by the user. So, if the user gives input string "there" and press Enter key, the fgets() reads the characters from the input stream and stores them in the buffer like this:

+---------------------------+
| t | h | e | r | e | \n| \0|
+---------------------------+
                      ^^

Remove the trailing newline character from the input buffer before passing it to the function which looks for the substring in the linked list:

inbuffer[strcspn(inbuffer, "\n")] = 0; //inbuffer is buffer which holds input string given by user
H.S.
  • 11,654
  • 2
  • 15
  • 32