Efficient way to check if std::string has only spaces

Viewed 63517

I was just talking with a friend about what would be the most efficient way to check if a std::string has only spaces. He needs to do this on an embedded project he is working on and apparently this kind of optimization matters to him.

I've came up with the following code, it uses strtok().

bool has_only_spaces(std::string& str)
{
    char* token = strtok(const_cast<char*>(str.c_str()), " ");

    while (token != NULL)
    {   
        if (*token != ' ')
        {   
            return true;
        }   
    }   
    return false;
}

I'm looking for feedback on this code and more efficient ways to perform this task are also welcome.

13 Answers

I had a similar problem in a programming assignment, and here is one other solution I came up with after reviewing others. here I simply create a new sentence without the new spaces. If there are double spaces I simply overlook them.

string sentence; string newsent; //reconstruct new sentence string dbl = " ";

getline(cin, sentence);

int len = sentence.length();

for(int i = 0; i < len; i++){

//if there are multiple whitespaces, this loop will iterate until there are none, then go back one.
    if (isspace(sentence[i]) && isspace(sentence[i+1])) {do{ 
        i++;
    }while (isspace(sentence[i])); i--;} //here, you have to dial back one to maintain at least one space.  
    
    
    newsent +=sentence[i];
}       

cout << newsent << "\n";

Related