Trim white space from string 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;
}
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 &lt;&lt; t &lt;&lt; "\n" 

// Output
this


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

std::string trim(std::string const&amp; str)
{
    std::string word;
    std::stringstream stream(str)
    stream &gt;&gt; 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&amp; 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.