I have a string which starts out with a lot of sp开发者_开发百科aces. If I want to find out the position of the first character that is not a space, how would I do that?
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);
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).
精彩评论