tags:

views:

223

answers:

3

I have a string which starts out with a lot of spaces. If I want to find out the position of the first character that is not a space, how would I do that?

+9  A: 

See string::find_first_not_of.

To find the position (index) of the first non-space character:

str.find_first_not_of(' ');

To find the position (index) of the first non-blank character:

str.find_first_not_of(" \t\r\n");

It returns str.npos if str is empty or consists entirely of blanks.

You can use find_first_not_of to trim the offending leading blanks:

str.erase(0, str.find_first_not_of(" \t\r\n"));

If you do not want to hardcode which characters count as blanks (e.g. use a locale) you can still make use of isspace and find_if in more or less the manner originally suggested by sbi, but taking care to negate isspace, e.g.:

string::iterator it_first_nonspace = find_if(str.begin(), str.end(), not1(isspace));
// e.g. number of blank characters to skip
size_t chars_to_skip = it_first_nonspace - str.begin();
// e.g. trim leading blanks
str.erase(str.begin(), it_first_nonspace);
vladr
A: 

What about the following?

string sample = "      Some string beginning with space chars";
char firstNonEmptyChar;
string::iterator stringIter = str.begin();

while ( stringIter != sample.end() && *stringIter != ' ' ) {
 stringIter++;
}
firstNonEmptyChar = *stringIter;

//Now, firstNonEmptyChar contains what you were looking for

you can esily customize the "while" condition in order to match whatever you need.

pfari
Nothing wrong with the code. But it is worth getting to know the string interface.
Martin York
+2  A: 

I have only one question: do you actually need the extra blanks ?

I would invoke the power of Boost.String there ;)

std::string str1 = "     hello world!     ";
std::string str2 = boost::trim_left_copy(str1);   // str2 == "hello world!     "

There are many operations (find, trim, replace, ...) as well as predicates available in this library, whenever you need string operations that are not provided out of the box, check here. Also the algorithms have several variants each time (case-insensitive and copy in general).

Matthieu M.