How to count how many different vowels are in one

2019-03-05 23:02发布

I am confused about counting how many differents vowels are in one word? This is were i got so far... I am saving word by word in the variable word[] and then check char by char whether is vowel or not... but i don't know how to count how many different vowels are in the word? Please help. Thanks in advance.

int i,j,words = 0;
while(fgets(row,MAX,f) != NULL)
{
    int flag = 0;
    int n = 0;

    for(i = 0; i < strlen(row); i++)
    {
        if(isalpha(row[i]))
        {
            if(!flag)
            {
                flag = 1;
            }
            word[n++] = row[i];
        }
        else if(flag)
        {
            flag = 0;
            word[n] = '\0';

            for(j = 0; j < strlen(word);j++)
            {
                if(isvowel(word[i]))
                {
                    c = word[i];
                }
                // i stopped here cause i donno how to check whether the char is different from all the others
            }
        }
    }
}

标签: count letters
2条回答
Animai°情兽
2楼-- · 2019-03-05 23:21

Okay it seems like the function for counting the different vowels in one word is created manually, but this solution really works and here it is:

int diff_vowels(char *word)
{
    char a = 'a',b = 'e', c = 'i', d = 'o', e = 'u';
    int a1 = 0,b1 = 0,c1 = 0,d1 = 0,e1 = 0;
    while(*word)
    {
        if(isalpha(*word))
        {
            if(tolower(*word) == 'a') a1 = 1;
            else if(tolower(*word) == 'e') b1 = 1;
            else if(tolower(*word) == 'i') c1 = 1;
            else if(tolower(*word) == 'o') d1 = 1;
            else if(tolower(*word) == 'u') e1 = 1;
        }
        word++;
    }
    return a1 + b1 + c1 + d1 + e1;
}
查看更多
爷、活的狠高调
3楼-- · 2019-03-05 23:23

As you find each vowel, simple set a flag of an array to note the vowel was found. Then count the number of flags. The trick is to effectively convert c (the vowel) into an index - that is where you are stuck.

char *strchr(const char *s, int c) is useful. It locates the first occurrence of (char) c in the string pointed to by s. Converting the result to an index for the flag array is then easy.

Let's say 'A' is the same as 'a' for vowel counting.

int DifferentVowelCount(const char *s) {
  static const char *Vowels = "AaEeIiOoUu";
  bool VowelExist[5] = { 0 };
  while (*s) {
    char *p = strchr(Vowels, *s);
    if (p != NULL) {
      int index = (int) (p - Vowels);  // index is 0 to 9
      index /= 2;
      VowelExist[index] = 1;
    }
    s++;
  }
  int sum = 0;
  int i;
  for (i = 0; i < 5; i++) {
    if (VowelExist[i]) {
      sum++;
    }
  }
  return sum;
}
查看更多
登录 后发表回答