Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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?

like image 406
neuromancer Avatar asked Feb 27 '10 08:02

neuromancer


2 Answers

See std::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);
like image 165
vladr Avatar answered Sep 20 '22 12:09

vladr


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).

like image 37
Matthieu M. Avatar answered Sep 19 '22 12:09

Matthieu M.