[英]How to find the first character in a 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? 如果我想找出第一个不是空格的角色的位置,我该怎么做?
See std::string::find_first_not_of
. 请参见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. 如果str
为空或完全由空白组成,则返回str.npos
。
You can use find_first_not_of
to trim the offending leading blanks: 您可以使用find_first_not_of
修剪有问题的前导空格:
str.erase(0, str.find_first_not_of(" \t\r\n"));
If you do not want to hardcode which characters count as blanks (eg 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
, eg: 如果您不想硬编码哪些字符计为空格(例如使用区域设置 ),您仍然可以find_if
使用find_if
最初建议的方式使用isspace
和find_if ,但要注意否定isspace
,例如:
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 ;) 我会在那里调用Boost.String的力量;)
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. 有许多操作( find
, trim
, replace
,...)以及此库中可用的谓词,只要您需要未开箱即用的string
操作,请在此处查看。 Also the algorithms have several variants each time (case-insensitive and copy in general). 此外,算法每次都有几个变量(不区分大小写并且通常复制)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.