【发布时间】:2020-07-13 07:43:10
【问题描述】:
这个函数应该返回字符串中元音的第一个实例,但它只适用于小写。我认为regex_constants::icase 也应该处理大写字母。另外,请随时提出更好的方法来做到这一点。
以下内容为“HAPPY”返回 0(现在返回 -1),为“GREaT”返回 3:
#include <regex>
int firstVowel(std::string str)
{
std::smatch match;
std::regex pattern("[aeiou]", std::regex_constants::icase);
while (std::regex_search(str, match, pattern))
{
return match.position();
}
return -1;
}
我通过 main 获得回报:
std::cout << firstVowel("HAPPY") << "\n";
std::cout << firstVowel("GREaT") << "\n";
【问题讨论】:
-
一个简单的方法是
"[aAeEiIoOuU]"。另外,请使用if,而不是while。看来that works -
@WiktorStribiżew 知道为什么这段代码不起作用(我也测试了
if)吗? -
你可能正在使用一个“糟糕”的编译器,它的
std::regex实现很差。 -
我正在使用 clang 编译,
HAPPY生成1作为返回值,2生成GREaT -
我正在使用 Visual Studio。我应该使用其他东西吗?