Occurrence of letter in string - C

Asked

Viewed 540 times

-1

Good afternoon,

My goal is to insert a string of up to 500 characters, and then read a letter. Creating, for this purpose a function that counts how many times that letter appears in the text.

The problem is that I must pass the text by reference to the function and I do not know if it is working. The function should receive the text, the letter and return the number of repetitions of the letter.

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

int contagem(char *txt, char letra)
{
    int contagem=0;
    int i;

    for (i=0; txt[i] !='\0';i++)
    {
        if (txt[i]==letra)
            contagem++;
    }
return contagem;
}


int main()
{
char txt[501],letra;

printf("Insira o texto:");
scanf("%s", txt);

printf("Deseja contar ocorrencia de qual letra?");
scanf(" %c", letra);

printf("O caracter aparece %d vezes \n", contagem(*txt,letra));
}
  • Here: scanf(" %c", letra); lacked the &: scanf(" %c", &letra);. Here: contagem(*txt,letra) the correct is: contagem(txt, letra).

  • I made this correction, however, after inserting the string and the letter I want to search, the command prompt freezes and closes.

  • Differentiate the variable name used to count from the function name. If your string has space characters, replace %sfor [^\n], otherwise the program will close the reading on the first space. See working on: https://ideone.com/Psm2UM

1 answer

0


When you pass an array by reference to a function, in its call you simply put the name of the identifier of it, in your case:

contagem(txt, letra);

This should solve your problem, but there’s a hint: you’re visibly new, so get the custom to test your code with smaller samples. Take a text with 10 words and test if your program is working, is the best way to answer your question "I don’t know if it’s working".

  • Thank you so much!! Solved the problem, I’m trying to learn alone so I’m encountering some difficulties even.

Browser other questions tagged

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