How to count how many different vowels are in one word from text file in C?

无人久伴 提交于 2019-12-04 06:15:42

问题


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
            }
        }
    }
}

回答1:


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;
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/25462491/how-to-count-how-many-different-vowels-are-in-one-word-from-text-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!