How to trim a std::string in C++

There is no standard way of trimming a string, but it’s possible to implement using the methods in the string class:

  • Left trim: Use find_first_not_of() to find the characters to erase
  • Right trim: Use find_first_of() to find the characters to erase
  • Trim: Do a right trim followed by a left trim (or vice-versa)

Use erase() to actually erase the characters.

Here is my implementation. It defaults to trimming whitespace characters but you can specify any string of characters as the second argument.

std::string& ltrim(std::string& str, const std::string& chars = "\t\n\v\f\r ")
{
    str.erase(0, str.find_first_not_of(chars));
    return str;
}

std::string& rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r ")
{
    str.erase(str.find_last_not_of(chars) + 1);
    return str;
}

std::string& trim(std::string& str, const std::string& chars = "\t\n\v\f\r ")
{
    return ltrim(rtrim(str, chars), chars);
}

Here’s a test program:

int main()
{
    std::string strings[] = {"", " ", "test", " test", "test ", " test "};
    const size_t n = sizeof(strings) / sizeof(std::string);
    for (unsigned int i = 0; i < n; ++i) {
        std::string str = strings[i];
        trim(str);
        std::cout << "\"" << str << "\"" << "\n";
    }
}

And here’s the valgrind output:

==23049== Memcheck, a memory error detector
==23049== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==23049== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==23049== Command: ./trim
==23049==
""
""
"test"
"test"
"test"
"test"
==23049==
==23049== HEAP SUMMARY:
==23049==     in use at exit: 0 bytes in 0 blocks
==23049==   total heap usage: 16 allocs, 16 frees, 475 bytes allocated
==23049==
==23049== All heap blocks were freed -- no leaks are possible
==23049==
==23049== For counts of detected and suppressed errors, rerun with: -v
==23049== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Related