2

This function is supposed to return the first instance of a vowel in a string, but it only works on lowercase. I thought regex_constants::icase was supposed to handle uppercase letters as well. Also, feel free to suggest a better way to do this.

The following returns 0 (it now returns -1) for "HAPPY" and 3 for "GREaT":

#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;
}

I'm getting the returns through main:

std::cout << firstVowel("HAPPY") << "\n";
std::cout << firstVowel("GREaT") << "\n";
Eric Xu
  • 306
  • 3
  • 10

1 Answers1

2

Please do not use that library icase: C++11 regex::icase inconsistent behavior it is terrible....

Instead switch the string to lowercase like so:

std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });

If you are using non-standard ASCII chars than you are on your own, there is no upper to lower for Greek Letters, Chinese Characters, Romanian Letters, and the like....

Yunfei Chen
  • 630
  • 1
  • 8
  • 20
  • Is there a difference in using `unsigned char` vs `char`? – Eric Xu Jul 12 '20 at 23:51
  • 1
    https://stackoverflow.com/questions/75191/what-is-an-unsigned-char, In your case either one works, but just for safety reasons, I use unsigned char.... – Yunfei Chen Jul 12 '20 at 23:53