Check the occurrence of each letter in a string - C

Asked

Viewed 1,169 times

0

I need to write a procedure that takes a pointer to a string p and shows(prints) the number of occurrences of each letter within the word. Example: macaw should show a=3 and r=2 shoe should show s=1, a=2, t=1 and o=1

I was trying to think of a logic in pure C but I can’t. Could you help me?

  • Set an array of integers of sufficient size for each letter of the alphabet (letter[27]) and initialize with 0. Scroll through its string, character by character, and taking advantage of a particularity of C do: letter[tplower(word[i]) - 'a']+++. At the end print each letter element that is non-zero. To know which letter is just add 'a' to the index.

2 answers

0

void verifiRepetition(char [],int);

void check Existence(char [],char, int *);

int main(){

int const quantodadeElementos = 50;
char vetorPalavra[quantodadeElementos];

printf("Informe uma palavra: ");
scanf("%s", vetorPalavra);

verificarRepeticao(vetorPalavra,quantodadeElementos);

return 0;

}

void checkRepetition(char vectorPalavra[], int quantityElements){

int contador = 0, i = 0, j = 0, teste = 0;
char charVerificaAtual, vetorPalavraDois[quantidadeElementos];

for(i=0;i<quantidadeElementos;i++){
    vetorPalavraDois[i] = '\0';
}

for(i=0;vetorPalavra[i]!='\0';i++){
    charVerificaAtual = vetorPalavra[i];
    verificarExistencia(vetorPalavraDois,charVerificaAtual,&teste);
    if(teste == 1){

    }else if(teste == 0){
        for(j=0;vetorPalavra[j]!='\0';j++){
            if(charVerificaAtual == vetorPalavra[j]){
                contador++;
            }
        }
    vetorPalavraDois[i]=charVerificaAtual;
    printf("%c Ocorreu %d.\n", charVerificaAtual,contador);
    contador = 0;
    teste = 0;

    }
}

} void checkExistence(char vectorPalavraDois[], char charVerificaAtual, int *test){

int i=0, testedois = 0;

for(i=0;vetorPalavraDois[i] != '\0';i++){
    if(charVerificaAtual == vetorPalavraDois[i]){
        testedois = 1;
        break;
    }
}
*teste = testedois;

}

-1


void procedure (char *palavra){
    int cont, x=0, cont2;
    char letra;

    for (cont=0; cont<strlen(palavra); cont++){
        letra=palavra[cont];
        for (cont2=0; cont2<strlen(palavra); cont2++){
            if(letra==palavra[cont2]){
                x++;
            }
        }
        printf ("\nocorrencias da letra %c = %d", letra, x);    
        x=0;
    }
}

main(){

    char word[20];
    char *p = word;
    printf ("Digite uma palavra: ");
    fflush(stdin);
    gets(p);
    procedure(p);
}
  • 1

    Avoid answering only with code. Explain your solution a little bit.

Browser other questions tagged

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