【问题标题】:How to find the first character in a C++ string如何找到 C++ 字符串中的第一个字符
【发布时间】:2010-02-27 08:54:47
【问题描述】:

我有一个以很多空格开头的字符串。如果我想找出不是空格的第一个字符的位置,我该怎么做?

【问题讨论】:

  • 你的字符串是什么编码的?如果是 ASCII,那么只有 4 个空白字符,Vlad 的 find_first_not_of 解决方案很好。 ASCII 或 Latin 1 字符串可能涵盖教学练习。如果您的字符串是 UTF-8 或宽字符 std::wstring(因为它可能在实际应用程序中),那么再问一个问题。
  • 是的,在这种情况下,可以在同一篇文章的底部使用find_if 解决方案(可选地使用BLL 的boost::labda::bind(isspace, _1, my_locale) 将特定语言环境my_locale 绑定到isspace而不是使用默认值)。

标签: c++ string


【解决方案1】:

std::string::find_first_not_of

查找第一个非空格字符的位置(索引)

str.find_first_not_of(' ');

查找第一个非空白字符的位置(索引):

str.find_first_not_of(" \t\r\n");

如果str 为空或完全由空格组成,则返回str.npos

您可以使用find_first_not_of 修剪有问题的前导空格:

str.erase(0, str.find_first_not_of(" \t\r\n"));

如果您不想硬编码哪些字符算作空白(例如 使用语言环境),您仍然可以或多或少按照最初建议的方式使用 isspacefind_if sbi,但注意否定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);

【讨论】:

    【解决方案2】:

    我只有一个问题:你真的需要额外的空格吗?

    我会在那里调用Boost.String 的力量;)

    std::string str1 = "     hello world!     ";
    std::string str2 = boost::trim_left_copy(str1);   // str2 == "hello world!     "
    

    此库中有许多操作(findtrimreplace、...)以及谓词,当您需要未开箱即用的 string 操作时,请检查这里。此外,算法每次都有几个变体(不区分大小写和复制)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 2017-03-10
      • 2020-02-14
      • 2018-01-05
      • 2018-01-19
      • 2015-07-02
      相关资源
      最近更新 更多