HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Trim white space from string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
trimwhitespacefromstring

Problem

This function is intended to remove leading and trailing whitespace from a string. How can it be made more efficient? For example, can the two for loops be combined into one?

string trim(string str)
{
    int i = 0;
    for (char c : str)
    {
        if (!isspace(c))
            break;
        i++;
    }

    string trimmed = str.substr(i, (str.length()-i));

    i = 0;
    for (char c : str)
    {
        if (isspace(c))
            break;
        i++;
    }

    trimmed = trimmed.substr(0, i);
    return trimmed;
}

Solution

Your current implementation you will lose all but the first word:

std::string str("this is a sentence");
std::string t  = trim(str);

std::cout << t << "\n" 

// Output
this


If that is your intention then there is an easier way of doing that:

std::string trim(std::string const& str)
{
    std::string word;
    std::stringstream stream(str)
    stream >> word;

    return word;
}


If you want to trim space of the ends on the string, then I would use the string search functions [coliru demo]:

std::string trim(std::string const& str)
{
    if(str.empty())
        return str;

    std::size_t firstScan = str.find_first_not_of(' ');
    std::size_t first     = firstScan == std::string::npos ? str.length() : firstScan;
    std::size_t last      = str.find_last_not_of(' ');
    return str.substr(first, last-first+1);
}


Here is the string documentation. Boost also has some extra libraries on the subject.

Code Snippets

std::string str("this is a sentence");
std::string t  = trim(str);

std::cout << t << "\n" 

// Output
this
std::string trim(std::string const& str)
{
    std::string word;
    std::stringstream stream(str)
    stream >> word;

    return word;
}
std::string trim(std::string const& str)
{
    if(str.empty())
        return str;

    std::size_t firstScan = str.find_first_not_of(' ');
    std::size_t first     = firstScan == std::string::npos ? str.length() : firstScan;
    std::size_t last      = str.find_last_not_of(' ');
    return str.substr(first, last-first+1);
}

Context

StackExchange Code Review Q#40124, answer score: 10

Revisions (0)

No revisions yet.