How-To perform common string manipulations

The liberate/string/util.h header contains assorted string manipulation functions. This collection is far from comprehensive, but it does provide functionality not offered by the standard library without some extra work.

Upper-/lower-case strings

Upper-/lower-case strings
1assert("asdf" == liberate::string::to_lower("AsDf"));
2assert("ASDF" == liberate::string::to_upper("AsDf"));

Replace parts of a string

The example replaces spaces with underscores. Note that it’s perfectly possible to use longer needles and substitutes.

Replace occurrences of a string with something else
1auto result = liberate::string::replace(
2    "The quick brown fox jumped over the lazy dog.",
3    " ", "_");
4// => "The_quick_brown_fox_jumped_over_the_lazy_dog."

Find a substring in a string

Related to the above, we can find a needle in a haystack in a case insensitive manner.

Find a string (case insensitive)
1auto result = liberate::string::ifind(
2    "The QUICk brown fox jumped over the lazy dog.",
3    "QUIC");
4assert(result == 4);
5
6result = liberate::string::ifind(
7    "The QUICk brown fox jumped over the lazy dog.",
8    "foo");
9assert(result == -1);

Split a string along delimiters

We can also split a string along some delimiters. By default, this splits along whitespace, but we can use any collection of delimiters.

Split a string
1auto result = liberate::string::split(
2    "Hello, world!", ", !");
3assert(2 == result.size());
4assert(result[0] == "Hello");
5assert(result[1] == "world");