How to count specific characters

0

I'm doing a program that counts how many vowels there are in the word, I was able to do it, now I was trying to do just count a vowel in the word, for example Rafael, the appears 2 times, I want you to count only once, could you 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;
}
    
asked by anonymous 02.02.2018 / 13:36

2 answers

1

You can do this as follows.

#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;
}
    
02.02.2018 / 13:52
1

It can be done this way too, as in C has 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;
}
    
02.02.2018 / 14:04