1
I have two variables:
char s1[20];
char s2[20];
I’ll go get the input user of the two variables, and after this, I need to check whether s1
is contained in s2
, even a part of it. For this I will use a function called esta_contido()
who will make 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();
}
On the part of if
with for
I’m checking to see if s1
and s2
has some equal part, if they have it goes pro go, to verify which words are equal, after that he gives a output
pro user the words that are equal. In this I have already achieved some progress, but I need to give output
pro user not the letters, but the initial position in which is contained the string.
if (strstr(S1, s2) != NULL) { // contains }
– Reginaldo Rigo
Thanks for the code, what is missing is how I can know in what initial position is the letter in which it is contained. Using a for to traverse the entire string would work ?
– Monteiro
To
strstr
provides this information in a slightly less direct way. I think with a little bit of pointer arithmetic one rescues exactly this information you need– Jefferson Quesado
I’m new to C, and pointers are still a bit complex for me, could you explain to me a little more how I can do this check ? I looked at strchr() function but I’m not able to reproduce what I want, I’m now trying to convert char to int to be able to show the Dice of its position, but unsuccessfully too.
– Monteiro
Do you just want to get the position or do you want to make an algorithm that calculates the position? You don’t have to know anything about pointer in this case.
– Maniero
I just want to get the first position where the string is contained. Just as in the above example in which I gave, if the user enters for example with the string "algorithm" and then in another string "rhythm", it will return the first position in which it is contained, in this case position 4.
– Monteiro