Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains spaces/tabs/new lines (anything that's blank)?

Tags:

c++

I know there's an "isspace" function that checks for spaces, but that would require me to iterate through every character in the string, which can be bad on performance since this would be called a lot. Is there a fast way to check if a std::string contains only spaces?

ex:

function("       ") // returns true
function("    4  ") // returns false

One solution I've thought of is to use regex, then i'll know that it only contains whitespace if it's false... but i'm not sure if this would be more efficient than the isspace function.

regex: [\w\W] //checks for any word character(a,b,c..) and non-word character([,],..)

thanks in advance!

like image 648
unwise guy Avatar asked Jul 11 '12 02:07

unwise guy


2 Answers

Any method would, of necessity, need to look at each character of the string. A loop that calls isspace() on each character is pretty efficient. If isspace() is inlined by the compiler, then this would be darn near optimal.

The loop should, of course, abort as soon as a non-space character is seen.

like image 173
Ernest Friedman-Hill Avatar answered Oct 21 '22 17:10

Ernest Friedman-Hill


With a regular string, the best you can do will be of the form:

return string::find_first_not_of("\t\n ") == string::npos;

This will be O(n) in the worst case, but without knowing else about the string, this will be the best you can do.

like image 21
Yuushi Avatar answered Oct 21 '22 17:10

Yuushi