How to check if a string is contained in another in C?

1

I have two variables:

char s1[20];
char s2[20];

I will get the input of the user of the two variables, and after that, I need to check if s1 is contained in s2 , even a single part of it. For this I will use a function called esta_contido() that will do this check.

Example:

    s1 = "algoritmo"; 
    s2 = "ritmo";
    esta_contido(); retorna 4 --> pois ele retorna a primeira posição do caractere em que está contido.

My code:

char s1[20];
char s2[20];

void esta_contido() {

    printf("Digite uma string : ");
    scanf("%s",&s1);

    printf("Digite outra string : ");
    scanf("%s",&s2);


    if (strstr(s1, s2) != NULL) { 

    for(int i = 0; i < 20; i++) {
        if(s2[i] == s1[i]) {
            i = 20;
            printf("s2 : %s", &s2);
        }
    }

    }


}


int main() {
    setlocale(LC_ALL,"portuguese");

    esta_contido();


}

In the part of if with for I'm checking if s1 and s2 has some equal parts, if they have pro forma, to check which words are equal, after that it gives output pro user the words that are the same. In this I have already made some progress, but I need to give output to the user not the letters, but the initial position in which is contained the string .

    
asked by anonymous 19.06.2017 / 19:49

2 answers

3
Since there is already a ready function that takes a part of string , rather make a subtraction of where you found the second substring in the first string .

There are some other bugs in this code and it does not even compile.

#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);
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

If you want to check if strstr(s1, s2) is null to say that there is no string within the other.

    
19.06.2017 / 20:35
-1
#include<stdio.h>
#include<string.h>
void main(){
    char S1[100], S2[100];
    int i,j,c=0;
    printf("digite a string S1\n");
    gets(S1);
    printf("digite a string S2\n");
    gets(S2);
    if(strlen(S1)<=strlen(S2)){
        printf("S2 nao he substring de S1\n");
    }else{
        for(i=0;i<strlen(S1);i++){
            if(S2[0]==S1[i]){
                for(j=0;j<strlen(S2)-1;j++){
                    if(S2[j]==S1[i++])
                        c++;
                }
            }
            if(c==strlen(S2)){
                break;
        }
    }
    if(c==strlen(S2))
        printf("S2 he string de S1\n");
    else
        printf("S2 nao he string de s1\n");
    }
}
    
10.06.2018 / 17:10