如何查找C ++字符串中的第一个字符 [英] 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?
推荐答案
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");
它返回 str.npos
if <$
您可以使用 find_first_not_of
修剪违规的前导空白:
You can use find_first_not_of
to trim the offending leading blanks:
str.erase(0, str.find_first_not_of(" \t\r\n"));
如果您不想硬编码哪些字符作为空格(例如使用区域设置),您仍然可以使用 isspace
和 find_if
或者以 sbi 最初建议的方式,但是注意取消 isspace
,例如:
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);
这篇关于如何查找C ++字符串中的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!