我是c ++的新手......我试图创建一个接受字符串并仅返回字符串中的元音的函数。我需要使用子串来执行此操作。如果我使用只有1个元音的单词,则该函数可以正常运行...但是我已经测试了一些其他字符串并且它不起作用。你们中有人有什么建议吗?非常感谢!
#include <iostream>
using namespace std;
string vowel_search(string str)
{
string test = str;
string result = "";
for (int i = 0; i < test.length(); i++)
{
if (str[i] == 'a' || str[i] == 'A'||
str[i] == 'e' || str[i] == 'E' ||
str[i]== 'i'|| str[i] == 'I' ||
str[i] == 'o' || str[i] == 'O' ||
str[i] == 'u' || str[i] == 'U')
{
result += test.substr(i, i);
}
}
return result;
}
int main() {
string strWord = "Aaron";
string str1 = vowel_search(strWord);
cout << str1 << endl; // prints out: aon
string strWord1 = "Harry";
string str2 = vowel_search(strWord1);
cout << str2 << endl; //prints out: a -- Correct
string strSentence = "Harry is Funny";
string str3 = vowel_search(strSentence);
cout << str3 << endl; //prints out: ais Fununny
return 0;
}
答案 0 :(得分:0)
result += test.substr(i, 1);
用1代替第二个i,1是字符数,或者你想要返回的长度