0

I have some string which I need to manipulate to be lowercase and replace some characters to blanks using regex.

The Java equivalent is:

str.toLowerCase();
str.replaceAll("[^a-z]", "");
str.replaceAll("\\s", "");

Within a c++03 constraint, and without using Boost or another library, how can I achieve the same functionality in C++? The version of g++ the server I am running on is 4.8.5 20150623.

Lowercasing is simple:

char asciiToLower(char c) {
    if (c <= 'Z' && c >= 'A') {
        return c - ('A' - 'a');
    }
    return c;
}

std::string manipulate(std::string str) {
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        it = asciiToLower(it);
    }
}

But what about the other two?

gator
  • 3,465
  • 8
  • 36
  • 76

1 Answers1

2

C++03 does not support regular expressions. This was introduced in C++11.

So, without (a) external libraries, or (b) writing a regex engine yourself, you can't.

However, GCC has regex support from 4.9, in the experimental -std=c++0x mode. So, if you can flip into that, and your GCC is new enough, maybe that can help you.

(Don't be misled into thinking that GCC 4.8 supports it: it doesn't; it's lying.)

Otherwise I suggest you update your compiler. Even C++11 is old now.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    Waiting for some smart alec to point out that you could do a `system()` call to the shell and get some OS utility to do it, then parse the response. I'm not counting that as a C++ solution. – Lightness Races in Orbit Oct 27 '19 at 20:05
  • Wouldn't work anyway. How would you extract the result? ``system`` only returns an int. This would require eg.: using external files to perform all processing. – Luis Machuca Oct 30 '19 at 15:47
  • @LuisMachuca Yep, the shell command could pipe the result to a file, then the C++ program could open the file to read it back in. Don't laugh: I've seen people do this crap in production. – Lightness Races in Orbit Oct 30 '19 at 17:07