How to find the first character in a C ++ string

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

+6
c ++ string
source share
2 answers

See std::string::find_first_not_of .

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

 str.find_first_not_of(' '); 

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

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

It returns str.npos if str empty or consists entirely of spaces.

You can use find_first_not_of to trim leading spaces:

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

If you don’t want to strictly indicate which characters are considered spaces (for example, use the locale ), you can still use isspace and find_if more or less the way sbi originally proposed, but take care of negating isspace , for example:

 string::iterator it_first_nonspace = find_if(str.begin(), str.end(), not1(isspace)); // eg number of blank characters to skip size_t chars_to_skip = it_first_nonspace - str.begin(); // eg trim leading blanks str.erase(str.begin(), it_first_nonspace); 
+15
source share

I have only one question: do you really need extra spaces?

I would use the Boost.String function 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. Algorithms also have several options each time (case insensitive and copying in general).

+5
source share

All Articles