How to count specific characters

Asked

Viewed 1,078 times

0

I’m making a program that counts how many vowels there are in the word, I managed to do, now I was trying to make only count a vowel in the word, for example Raphael, the appears 2 times, I want to count only once, could help me ?

#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
  char nome[100];
  char vogais[11]={"AEIOUaeiou"};
  int cont=0;
  scanf("%s",nome);
  for(int i=0;i<strlen(nome);i++)
 {
     for(int j=0;j<strlen(vogais);j++)
     {
         if(nome[i]==vogais[j])
         {
            cont++;
         }
     }
 }
  printf("%d\n",cont);
  return 0;
}
  • You want to know if a specific vowel is present or how many specific vowels there are?

  • How many vowels are in the word, not counting the vowels repeated in the word

2 answers

1


You can do it this way.

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

int main(int argc, char** argv) {
    char nome[100];
    char vogais[11] = {"AEIOUaeiou"};
    int cont = 0;
    int existeVogais[10];
    scanf("%s",nome);
    for(int i = 0; i < strlen(nome); i++) {
        for(int j = 0; j < strlen(vogais); j++) {
            if(nome[i] == vogais[j]) {
                existeVogais[j] = 1;
            }
        }
    }
    for (int i = 0; i < 10; i++) {
        if (existeVogais[i] == 1){
            printf("Existe a vogal %c\n",vogais[i]);
            cont += 1;
        }
    }
    printf("\nPortanto tempos %d vogais na palavra\n",cont);
    return 0;
}

1

It can be done that way too, as in C no boolean, we create one using integer variables:

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

int main(int argc, char** argv)
{
  char nome[100];
  char vogais[5]={"AEIOU"};
  int cont=0, a = 0, e = 0, i = 0, o = 0, u = 0;
  scanf("%s",nome);
  strupr(nome);
  for(int i=0; i < strlen(nome); i++)
  {
    for(int j=0; j < 5; j++)
    {
       if(nome[i]==vogais[j])
       {
           if(nome[i] == 'A') a++;
           else if(nome[i] == 'E') e++;
           else if(nome[i] == 'I') i++;
           else if(nome[i] == 'O') o++;
           else if(nome[i] == 'U') u++;
       }
    }

  }

if(a > 0) cont++;
if(e > 0) cont++;
if(i > 0) cont++;
if(o > 0) cont++;
if(u > 0) cont++;

printf("%d\n",cont);
return 0;
}
  • This way it is not very practical because we have to test the 10 options (you did only with capital letters). Not to mention the amount of testing that has to be done with each interaction, greatly increasing the processing time. Not that this will slow down the program (it’s a very simple program), but the ideal is to always pay attention to performance.

  • I uppercase all character strings using the function "strupr" then it won’t be a problem, already the performance really it is not so good but as you said yourself you are a simple program.

  • Phelipe, could you explain to me, that part exists Lawyers[j] = 1;

Browser other questions tagged

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