且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何查找C ++字符串中的第一个字符

更新时间:2021-11-26 21:33:27

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