Laime Nekurzeme
Laime Nekurzeme

Reputation: 33

Testing Index of String Array in c++?

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{

    char str[80];
    int i=0;
    cout<<"Enter the String ";
    gets(str);
    for (int j=0;str[j]!='\0';j++)
    if (str[i]=='A'||'E'||'I'||'O'||'U')
    i++;
    cout<<"Number of vowels is: "<<i;



}

Here i am check element in String for Vowel, can anyone please suggest alternate method for this? I need to count number of vowels in string.

This code is working perfect for me, just need to find alternate method where i don't have to type too much "||" and 'a' and 'A' differently.

Upvotes: 0

Views: 549

Answers (6)

Luchian Grigore
Luchian Grigore

Reputation: 258608

A more C++-ish solution:

std::string vowels("aAeEiIoOuU");
for (int j=0;str[j]!='\0';j++)
{
   if ( vowels.find(str[j]) != std::string::npos )
   i++;
}

Upvotes: 2

perreal
perreal

Reputation: 97948

Or use a table:

#include <iostream>
#include <string>

int main()
{
  char list_v[256] = { 0 };
  list_v['a'] = list_v['e'] = list_v['i'] = list_v['o'] = list_v['u'] = 1;
  list_v['A'] = list_v['E'] = list_v['I'] = list_v['O'] = list_v['U'] = 1;
  std::string str = "a sentence here";
  uint32_t cnt = 0;
  for (uint32_t i = 0; i < str.length(); i++)
     cnt += list_v[str[i]];
  std::cout << "found " << cnt << std::endl;
  return 0;
}

or use map for the same purpose, or a c++ array/vector, people don't like c arrays here. This only works for ASCII of course.

Upvotes: 0

111111
111111

Reputation: 16148

inline bool is_vowel(char a)
{
    a=std::tolower(a);
    switch(a)
    {
    case 'a':        case 'e':
    case 'i':        case 'o':
    case 'u':
        return true;
    }
    return false;
}

int main()
{
    std::string line;
    std::cout << "enter text" << std::endl;
    std::getline(std::cin, line);
    int vowel=std::count_if(line.begin(), line.end(), is_vowel);
    std::cout << "Number of vowels: " << vowel << std::endl;
}

Upvotes: 1

raj
raj

Reputation: 3811

Way? or syntax?

i think its a syntax error.. it should be like

if(str[i]=='A' || str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')

If you are asking about a better way, i don't think there is any.. You are doing in O(n) complexity, which is good enough i guess.! Even if you use hashing, you'll have to hash all the n characters in a string..

Upvotes: -2

Stefan Birladeanu
Stefan Birladeanu

Reputation: 294

if (str[i]=='A'||'E'||'I'||'O'||'U') 

this is wrong

should be like this:

if(str[i]=='A' || str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')

and also take care of case sensitiveness

Upvotes: 5

Fred Foo
Fred Foo

Reputation: 363567

str[i]=='A'||'E'||'I'||'O'||'U'

always returns true, because 'E' is always true. You're looking for

strchr("AEIOU", str[j])

Note the j, you got the loop variable wrong.

(Also, in C++, you'll want to use iostreams and getline instead of cstdio and fgets.)

Upvotes: 4

Related Questions