Check if a string is contained in another without the string.h library?

1

I need to check if a string is contained in another and returns the position where the first letter appeared.

I saw the following code here on the site, however I can not use the string.h library.

include stdio.h  
include string.h

int main()   
{  
    char s1[20];  
    char s2[20];  
    printf("Digite uma string : ");  
    scanf("%s", s1);  
    printf("Digite outra string : ");  
    scanf("%s", s2);  
    printf("%ld", strstr(s1, s2) - s1);  
}  

I tried to do it as follows:

void str_conteudo( char str1[], char str2[])
{  
int i=0;
int y;

while(str1[i] == str2[i] && str2[i] != 0) 
{
    if (str2[i] != str1[i])
        return i;
    i++;
}

y=i;
printf("Indice do primeiro caractere que contem a string 2: %d ", y);

}

But it is not increasing, what can be wrong?

    
asked by anonymous 15.06.2018 / 22:59

1 answer

0

Just take a look at the function code strstr and copy and paste it .

Disregarding the header and documentation comments, here's the code:

char *
strstr(string, substring)
    register char *string;  /* String to search. */
    char *substring;        /* Substring to try to find in string. */
{
    register char *a, *b;

    /* First scan quickly through the two strings looking for a
     * single-character match.  When it's found, then compare the
     * rest of the substring.
     */

    b = substring;
    if (*b == 0) {
        return string;
    }
    for ( ; *string != 0; string += 1) {
        if (*string != *b) {
            continue;
        }
        a = string;
        while (1) {
            if (*b == 0) {
                return string;
            }
            if (*a++ != *b++) {
                break;
            }
        }
        b = substring;
    }
    return NULL;
}

There are a few things that can be changed, especially the archaic K & R notation of declaring the parameter types between ) and { to be replaced by current notation, the register modifier that can be ignored in modern compilers and += 1 that can be replaced by ++ , among other small possible changes. However, the code is essentially this and anything else you do, assuming it is correct, will be equivalent to that.

    
15.06.2018 / 23:36