为什么代码没有删除"u"?从输入字符串? [英] Why is the code is not removing "u" from the input string?
本文介绍了为什么代码没有删除"u"?从输入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习C ++.今天,我已经编写了一个代码,以删除字符串中的元音.在某些测试中它工作正常.但是该测试未能消除"u"标记.从一个字符串.我的输入是: tour
.输出为: tur
.但是我期望像 tr
这样的输出用于 tour
I am learning C++. Today I have written a code to remove vowels form a string. It works fine in some tests. But this test is failing to remove "u" from a string.
My input was: tour
.
Output was: tur
.
But I am expecting the output like tr
for tour
代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string word;
getline(cin, word);
transform(word.begin(), word.end(), word.begin(), ::tolower); // Converting uppercase to lowercase
for (int i = 0; i < word.length(); i++)
{
if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'o' || word[i] == 'u')
{
word.erase(word.begin() + i); // Removing specific character
}
}
cout << word << endl;
return 0;
}
我该怎么做?代码中的问题在哪里?
How can I do that? Where is the problem in the code?
推荐答案
擦除
后,执行 i ++
.这意味着支票会绕过一个元素.
After erase
, i++
is performed. That means one element is bypassed by the check.
将 for
循环更改为
for (int i = 0; i < word.length(); )
{
if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'o' || word[i] == 'u')
{
word.erase(word.begin() + i); // Removing specific character
}
else
{
i++; // increment when no erasion is performed
}
}
这篇关于为什么代码没有删除"u"?从输入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文