在字符串中反转元音时出错

Getting an error while reversing vowels in a string

本文关键字:出错 字符串      更新时间:2023-10-16

我知道关于这个主题也有类似的问题,但我想知道我的方法有错误。

我正在编写一个代码来反转字符串中的元音。我首先将字符串的所有元音放入向量中,然后通过替换元音从向后循环字符串,但我不断收到错误。

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
string reverseVowels(string s)
{
vector<char>v;
vector<char>v2;
char c;
for (int i = 0; i < s.size(); i++)
{
//taking all the vowels of the string into a vector
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
v.push_back(s[i]);
}
}
//reversing the vowels of the string
for (int i = s.size() - 1; i >= 0; i--)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
s[i] = v[i];  //Getting an error here
}
}
return s;
}
int main()
{
//Required output is "holle"
string s = "hello";
string p = reverseVowels(s);
cout << p << endl;
return 0;
}

你需要另一个反转元音的索引:

for (int vowelIdx = 0, i = s.size() - 1; i >= 0; i--)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
{
s[i] = v[vowelIdx++];  //Getting an error here
}
}

编辑

关于您在下面的评论; 让我们检查单词的代码hello.第一个循环贯穿hello中的所有元音,并将向量v填充为eo。它有两个元音,e是第一个元音,o是第二个/最后一个元素。

你的第二个循环反向遍历单词hello,并遇到第一个元音o。您需要将其重置为e这是向量v的第一个元素。这是您的代码出现错误的地方。i的值现在4,因此您尝试使用只有两个元素的向量v的 4.th 索引。您必须设置s[4] = v[0]s[1] = v[1]。但是,您的代码尝试设置s[4] = v[4](请参阅错误?)并s[1] = v[1]

希望现在清楚了,如果不尝试在纸上用更长的单词。我相信你会明白这一点。