我正在尝试使用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;
访问向量元素的成员函数不是您的问题。您的 if 语句格式错误。目前,您正在将子字符串与一个长字符串进行比较,在这种情况下,它永远不会计算为 true。
如果你想检查特定字符,你将需要这样的东西:
bool is_vowel(char c) {
c = tolower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
Or...
bool is_vowel(char c) {
switch(tolower(c)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
现在你可以像这样调用你的函数:
std::string s = vec[i];
if(is_vowel(s[n])) {
// the third character is a vowel
}
您的代码还存在一些其他问题。这行:
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;
要将项目添加到矢量末尾,您需要做的就是:
vec.push_back(s);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)