Programação Imperativa

100 Questões Fichas Testes/Exames

Questão 10: strstr

Voltar

Apresente uma definição da função pré-definida em C char *strstr (char s1[], char s2[]) que determina a posição onde a string s2 ocorre em s1. A função deverá retornar NULL caso s2 não ocorra em s1.

Exemplo

> strstr("Programacao", "grama")
(char *) "gramacao"
> strstr("Imperativa", "pedra")
(char *) NULL

Resolução

char* mystrstr (char haystack[], char needle[]) {
    int Nh, Nn, found;
    for(Nh = 0; haystack[Nh]; Nh++) {
        found = 1;
        for(Nn = 0; needle[Nn]; Nn++)
            if(needle[Nn] != haystack[Nh + Nn])
                found = 0;
        if(found == 1) break;
    }
    if(found == 1) return haystack + Nh;
    return NULL;
}