Removing leading and trailing spaces from a string

How to remove spaces from a string object in C++.
For example, how to remove leading and trailing spaces from the below string object.

//Original string: "         This is a sample string                    "
//Desired string: "This is a sample string"

The string class, as far as I know, doesn’t provide any methods to remove leading and trailing spaces.

To add to the problem, how to extend this formatting to process extra spaces between words of the string. For example,

// Original string: "          This       is         a sample   string    " 
// Desired string:  "This is a sample string"  

Using the string methods mentioned in the solution, I can think of doing these operations in two steps.

  1. Remove leading and trailing spaces.
  2. Use find_first_of, find_last_of, find_first_not_of, find_last_not_of and substr, repeatedly at word boundaries to get desired formatting.


This is called trimming. If you can use Boost, I’d recommend it.

Otherwise, use find_first_not_of to get the index of the first non-whitespace character, then find_last_not_of to get the index from the end that isn’t whitespace. With these, use substr to get the sub-string with no surrounding whitespace.

In response to your edit, I don’t know the term but I’d guess something along the lines of “reduce”, so that’s what I called it. 🙂 (Note, I’ve changed the white-space to be a parameter, for flexibility)

#include <iostream>
#include <string>

std::string trim(const std::string& str,
                 const std::string& whitespace = " t")
    const auto strBegin = str.find_first_not_of(whitespace);
    if (strBegin == std::string::npos)
        return ""; // no content

    const auto strEnd = str.find_last_not_of(whitespace);
    const auto strRange = strEnd - strBegin + 1;

    return str.substr(strBegin, strRange);

std::string reduce(const std::string& str,
                   const std::string& fill = " ",
                   const std::string& whitespace = " t")
    // trim first
    auto result = trim(str, whitespace);

    // replace sub ranges
    auto beginSpace = result.find_first_of(whitespace);
    while (beginSpace != std::string::npos)
        const auto endSpace = result.find_first_not_of(whitespace, beginSpace);
        const auto range = endSpace - beginSpace;

        result.replace(beginSpace, range, fill);

        const auto newStart = beginSpace + fill.length();
        beginSpace = result.find_first_of(whitespace, newStart);

    return result;

int main(void)
    const std::string foo = "    too mucht   tspacettt  ";
    const std::string bar = "onentwo";

    std::cout << "[" << trim(foo) << "]" << std::endl;
    std::cout << "[" << reduce(foo) << "]" << std::endl;
    std::cout << "[" << reduce(foo, "-") << "]" << std::endl;

    std::cout << "[" << trim(bar) << "]" << std::endl;


[too much               space]  
[too much space]