如何判断一个字符是否是元音

Der*_*ick 0 c++

我正在尝试使用vector[].substr(),但我不知道这是否可能。有谁知道另一种方法可以做到这一点?我的目标是取出一个向量中的单词并将其与第一个元音分开。任何帮助表示赞赏。我的代码如下所示:

#include <iostream>
#include "derrick_math.h"
#include <string>
#include <sstream>
#include <vector>
#include <cctype>
#include <algorithm>
using namespace std;

int main()
{
    string phrase;
    string ay = "ay";
    vector<string> vec;
    cout << "Please enter the word or phrase to translate: ";
    getline(cin, phrase);

    istringstream iss(phrase);
    copy(istream_iterator<string>(iss), 
         istream_iterator<string>(), 
         back_inserter(vec));
    for (int i = 0; i < vec.size(); i++)
    {
        if (vec[i].substr(0, 1) == "a || e || i || o || u || A || E || I || O || U")
    {
        cout << vec[i] << "ay";
    }
    if (vec[i].substr(1, 1) == "a || e || i || o || u || A || E || I || O || U")
    {
        cout << vec[i].substr(2) << vec[i].substr(0, 1) << "ay";
    }
    if (vec[i].substr(2, 1) == "a || e || i || o || u || A || E || I || O || U")
    {
        cout << vec[i].substr(3), vec[i].substr(0, 2) + "ay";
    }
    if (vec[i].substr(3, 1) == "a || e || i || o || u || A || E || I || O || U")
    {
        cout << vec[i].substr(4), vec[i].substr(0, 3) + ay;
    }
    cout << vec[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
Run Code Online (Sandbox Code Playgroud)

Ed *_* S. 5

访问向量元素的成员函数不是您的问题。您的 if 语句格式错误。目前,您正在将子字符串与一个长字符串进行比较,在这种情况下,它永远不会计算为 true。

如果你想检查特定字符,你将需要这样的东西:

bool is_vowel(char c) {
    c = tolower(c);
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
Run Code Online (Sandbox Code Playgroud)

或者...

bool is_vowel(char c) {
    switch(tolower(c)) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        return true;
    default:
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样调用你的函数:

std::string s = vec[i];
if(is_vowel(s[n])) {
    // the third character is a vowel
}
Run Code Online (Sandbox Code Playgroud)

您的代码还存在一些其他问题。这行:

cout << vec[i].substr(4), vec[i].substr(0, 3) + ay;
Run Code Online (Sandbox Code Playgroud)

大概应该是:

// no comma operator
cout << vec[i].substr(4) << vec[i].substr(0, 3) + ay;
Run Code Online (Sandbox Code Playgroud)

要将项目添加到矢量末尾,您需要做的就是:

vec.push_back(s);
Run Code Online (Sandbox Code Playgroud)

  • [`find_first_of`](http://en.cppreference.com/w/cpp/string/basic_string/find_first_of) 会让事情变得更容易:`s.find_first_of("AEIOUaeiou")`。 (2认同)