我正在尝试使用 vector [].substr(),但我不知道这是否可行.有谁知道另一种方式来做到这一点?我的目标是取一个向量中的单词,并将其与第一个元音分开.任何帮助表示赞赏.我的代码如下:
I am trying to get use vector[].substr() but i don't know if this is possible. Does anyone know another way to do this? My goal is to take a word that is in vector and separate it from the first vowel. any help is appreciated. my code looks like :
#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; 推荐答案访问矢量元素的成员函数不是您的问题.您的if语句格式错误.当前,您正在将子字符串与一个长字符串进行比较,在这种情况下,该值永远不会为true.
Accessing the member functions of your vector's elements is not your problem. Your if statements are malformed. Currently you are comparing the substring against one long string, and that will never evaluate to true in this case.
如果要检查特定字符,则将需要以下内容:
If you want to check for a specific character you will need something like this:
bool is_vowel(char c) { c = tolower(c); return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; }或者...
bool is_vowel(char c) { switch(tolower(c)) { case 'a': case 'e': case 'i': case 'o': case 'u': return true; default: return false; } }现在您可以像这样调用函数了:
Now you can call your function like so:
std::string s = vec[i]; if(is_vowel(s[n])) { // the third character is a vowel }您的代码也存在其他一些问题.这行:
There are some other issues with your code as well. This line:
cout << vec[i].substr(4), vec[i].substr(0, 3) + ay;应该是:
// no comma operator cout << vec[i].substr(4) << vec[i].substr(0, 3) + ay;要将一个项目添加到向量的末尾,您需要做的是:
To add an item to the end of your vector, all you need is:
vec.push_back(s);更多推荐
如何确定角色是否为元音
发布评论