How to read each char of a string, to know if one is contained in the other, in C?

Asked

Viewed 39 times

-2

Good morning, good afternoon, good evening. I’m trying to make a statement from my C programming course that asks me to make a code that checks if a string2 is contained in a string1, using pointer arithmetic, I’ve tried in many ways to perform this exercise, but the only way I’ve found to do itlo is based on the method I will send here, but when executing the code I can verify that it contains only the first letters of string1, for example: if I type "brazil" for the first string and type "bra" for the second, it detects that it is contained, but if I type "brazil" for the first and "Sil" for the second, it does not detect that it is contained, I would like to know how to solve this problem. Thank you, I await your reply. Note: The statement is as a comment in the code, right below the libraries.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>

/*
18) Elabora uma função que receba duas strings como parâmetros e
verifique se a segunda string está dentro da primeira. Para isso, utilize
apenas aritmética de ponteiros.
*/

void verifica(const char* ptr1,const char* ptr2) {
  int l=0;
  for (size_t i = 0; i < strlen(ptr1); i++) {
   if (ptr1[i]==ptr2[i]) {
     l++;
    }//if
  }//for

  if (l == strlen(ptr2)) {
    printf("Está contida!! \n");
  }else{
    printf("Não está contida!! \n");
  }//ifelse
}//verifica

int main (){
  setlocale(LC_ALL, "Portuguese");
  char str1[21], str2[21];
  char *ptr[2] = {str1, str2};


  for (size_t i = 0; i < 2; i++) {
    printf("Digite a %dº palavra de até 20 caracteres: ", i + 1);
    fgets(ptr[i], 21, stdin);
    ptr[i][strcspn(ptr[i],"\n")]='\0';
    setbuf(stdin,NULL);
  }//for

  verifica(ptr[0],ptr[1]);


return 0;
}//main
   

1 answer

1

Hello. Understanding the question, I could notice that the problem is in the check of contained. Come on:

Think to me, I go from 0 to strlen(ptr1) -1. Correct?

We will use the same error inputs:

(brazil, Sil)

i at 0: string1 == b and string2 == s -> so the l does not increment

i in heading 1: string1 == r and string2 == i -> so the l does not increment

i at position 2: string1 == a and string2 == l -> so no increment l

The first problem is that in this case will never check. The second problem is that after that, i will continue increasing, even if there are no more letters in string2, and will start comparing the rest of the letters in string1 (Sil) with string2 trash.

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

this topic can help you a lot in this issue. It’s basically the same question.

  • vlw, thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.