user1906594
user1906594

Reputation:

how to find a vowel inside a string in c++?

how to find a vowel inside a string in c++? do I use "a" or 'a' or just the ascii value to look or vowels?

Upvotes: 1

Views: 12459

Answers (3)

Pete Becker
Pete Becker

Reputation: 76428

std::string vowels = "aeiou";
std::string target = "How now, brown cow?"
std::string::size_type pos = target.find_first_of(vowels);

Note that this does not use std::find_first_of, but the string member function with the same name. It's possible that the implementation provides an optimized version for string searches.

Upvotes: 1

Leonid Volnitsky
Leonid Volnitsky

Reputation: 9144

Use std::find_first_of algorithm:

string h="hello world"; 
string v="aeiou"; 
cout << *find_first_of(h.begin(), h.end(), v.begin(), v.end());

Upvotes: 3

Ed Swangren
Ed Swangren

Reputation: 124722

int is_vowel(char c) {
    switch(c)
    {
        // check for capitalized forms as well.
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            return 1;
        default:
            return 0;
    }
}

int main() {
    const char *str = "abcdefghijklmnopqrstuvwxyz";
    while(char c = *str++) {
        if(is_vowel(c))
            // it's a vowel
    }
}

EDIT: Oops, C++. Here is a std::string version.

#include <iostream>
#include <string>

bool is_vowel(char c) {
    switch(c)
    {
        // check for capitalized forms as well.
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            return true;
        default:
            return false;
    }
}

int main() {
    std::string str = "abcdefghijklmnopqrstuvwxyz";
    for(int i = 0; i < str.size(); ++i) {
        if(is_vowel(str[i]))
            std::cout << str[i];
    }

    char n;
    std::cin >> n;
}

Upvotes: 2

Related Questions