【问题标题】:std::string comparison (check whether string begins with another string)std::string 比较(检查字符串是否以另一个字符串开头)
【发布时间】:2010-10-30 05:32:06
【问题描述】:

我需要检查 std:string 是否以“xyz”开头。如何在不搜索整个字符串或使用 substr() 创建临时字符串的情况下做到这一点。

【问题讨论】:

    标签: c++ string stl compare


    【解决方案1】:

    我会使用比较方法:

    std::string s("xyzblahblah");
    std::string t("xyz")
    
    if (s.compare(0, t.length(), t) == 0)
    {
    // ok
    }
    

    【讨论】:

    • 为什么不简单地使用 s.compare(t)?
    • @FranckMesirard:这是因为默认情况下 compare 会尝试将传递的字符串的整个长度与成员数据进行比较,并返回 false,同时给出传递的长度参数的长度将使其返回 true(意思是 std::basic_string::compare,当与偏移量和长度一起使用时,可以像其他库中的 String.BeginsWith() 一样使用。)没有偏移量和长度,这是不正确的。
    • 如果 t 为空,则返回 true。
    • @gliderkite 应该...空字符串是每个字符串的初始前缀。
    • 应该是正确的...如果要排除空字符串: if (!t.empty() && !s.compare(0, t.length(), t))
    【解决方案2】:

    一种可能更符合标准库精神的方法是定义您自己的 begin_with 算法。

    #include <algorithm>
    using namespace std;
    
    
    template<class TContainer>
    bool begins_with(const TContainer& input, const TContainer& match)
    {
        return input.size() >= match.size()
            && equal(match.begin(), match.end(), input.begin());
    }
    

    这为客户端代码提供了一个更简单的接口,并且与大多数标准库容器兼容。

    【讨论】:

    • 酷!这应该被添加到提升!
    • @David:如果 boost 是允许的依赖项,请参见 boost::algorithm::starts_with — 'Starts with' 谓词
    【解决方案3】:

    查看 Boost 的String Algo 库,它有许多有用的函数,例如starts_with、istart_with(不区分大小写)等。如果您只想在项目中使用部分boost 库,那么您可以使用bcp 实用程序仅复制需要的文件

    【讨论】:

      【解决方案4】:

      看来std::string::starts_with在C++20里面,同时可以使用std::string::find

      std::string s1("xyzblahblah");
      std::string s2("xyz")
      
      if (s1.find(s2) == 0)
      {
         // ok, s1 starts with s2
      }
      

      【讨论】:

      • 这比使用std::string::compare 的公认答案要好得多,因为它可以轻松检查字符串是否以文字开头,而无需重复文字本身来查找其大小。并感谢您指出 C++20 直接解决方案。
      • 如果 s1 不以 s2 开头,后面还是会尝试匹配,不如 compare()。
      【解决方案5】:

      我觉得我没有完全理解你的问题。看起来应该是微不足道的:

      s[0]=='x' && s[1]=='y' && s[2]=='z'
      

      这只查看(最多)前三个字符。在编译时未知的字符串的泛化将需要您用循环替换上面的内容:

      // look for t at the start of s
      for (int i=0; i<s.length(); i++)
      {
        if (s[i]!=t[i])
          return false;
      }
      

      【讨论】:

      • 好吧,我知道如何在使用 C 函数时比较字符串。我的问题是关于通过 C++ STL 以面向对象的方式进行。
      • 这里没有使用 C 函数。并且标准库不会阻止您编写自己的函数。
      • 如果 t 比 s 短怎么办?
      • @jackhab STL 的作者说“STL 不是面向对象的。我认为面向对象几乎和人工智能一样是骗局。” -- stlport.org/resources/StepanovUSA.html
      • @vidstige 然后循环在遇到t中的终止NUL时终止。
      猜你喜欢
      • 2011-12-07
      • 2013-09-04
      • 2017-11-27
      • 2012-02-09
      • 2011-06-13
      • 1970-01-01
      • 2011-05-04
      • 2019-12-29
      • 2010-12-25
      相关资源
      最近更新 更多