Trimming strings in C++

Posted in software by Christopher R. Wirz on Mon Apr 02 2012



There are many reasons to use C++ over C. My personal biggest reason is std::string. It makes doing things on the stack so much easier. Just one problem: where is the trim() method?

We want one that does not modify the original string. The method must also return a stack-allocated copy. Well, let's make one:


/**
 * Returns a new string trimming spaces from front and back
 * @param str The original string
 */
std::string trim(const std::string &str)
{
    std::string s(str);
    while (s.size() > 0 && std::isspace(s.front()))
    {
        s.erase(s.begin());
    }
    while (s.size() > 0 && std::isspace(s.back()))
    {
        s.pop_back();
    }
    return s;
}

Now let's test it! We'll try spaces and line returns. We'll also test equality.


#include <iostream>

int main()
{
    std::cout << trim("          3  Hello World   3  \n");
    if (trim("\t          3  Hello World   3  \n") == "3  Hello World   3") {
        std::cout << "- trim removed line returns too!";
    }
    return 0;
}

Here are the results:

3  Hello World   3- trim removed line returns too!

We see that equality, and trimming of line returns works.

What's next? You can try the example online.