在字符串中反转元音时出错
Getting an error while reversing vowels in a string
我知道关于这个主题也有类似的问题,但我想知道我的方法有错误。
我正在编写一个代码来反转字符串中的元音。我首先将字符串的所有元音放入向量中,然后通过替换元音从向后循环字符串,但我不断收到错误。
#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]
。
希望现在清楚了,如果不尝试在纸上用更长的单词。我相信你会明白这一点。
相关文章:
- 重载操作程序时出错>>用于类中的字符串 memebr
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- 在 Rcpp 中的字符串类型之间转换时出错
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 读取字符串C++的字符时出错
- 读取字符串字符时出错 - 对于数组中的字符串值
- 通过字符串::插入插入字符时出错
- 使用来自串行端口的字符串数据来操作振镜扫描仪在更高的速度下会出错
- 通过 constexpr 中的 'const char *' glvalue 访问字符串文字的值会出错
- 读取字符串字符时出错
- 计算字符串中字符的出现次数时出错
- 在字符串中反转元音时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 在 c++ 中调用将字符串作为参数传递的函数时出错
- 使用 C++Builder 项目读取字符串中的文件时出错
- 在字符串流中使用来自 github 的代码时出错
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 从字符串中读取字符时出错
- std::out_of_range 比较字符串中的符号时出错