How to count occurrences of a substring in a string in c?

Asked

Viewed 56 times

0

That was the code I made but it’s not giving

#include <stdio.h>

int main()
{
  char tamanholetra[51], letra;
  int a, num;
  int end;
  int num2;

  //escaneia palavra
  scanf("%s", tamanholetra);
  getchar();
  //escaneia letra
  scanf("%s", &letra);
  
    //processo de comparação
  for (num = a = 0; tamanholetra[a] != '\0'; ++a) {
    if (tamanholetra[a] == letra) {
      ++num;
    }
  }
     
    num2 = strlen(tamanholetra);
    end = num2 - num;
    //tela usuario

  printf("Numero de ocorrencia: %d\n", end);

  return 0;
}
  • This scanf("%s", &letra); is with the wrong format specification, must be scanf("%c", &letra);. I didn’t understand your calculation of the number of occurrences, it seems that "letter" occurs "one" times in the string. Another thing is that you are not checking the occurrence of substrings but a single character.

No answers

Browser other questions tagged

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