【问题标题】:How to extract a substring from string beginning to the second delimiter?如何从字符串开头到第二个分隔符提取子字符串?
【发布时间】:2018-12-13 14:16:15
【问题描述】:

我的字符串是:std::string achRecBuff = "usbaudio_1_req:some string";

从那个字符串中,我想提取字符串直到第二个分隔符'_'。 所以提取的字符串应该像“usbaudio_1”。

我该怎么做?

【问题讨论】:

  • <regex> 来自 C++11 的标头应该适合您。
  • 展示你的作品,你尝试过什么?
  • 还有用例吗?字符串的格式是否始终相同?第二个下划线总是最后一个吗?是否总是有 2 个下划线?
  • 不,到目前为止,我只有 2 个下划线,给定的解决方案解决了我的问题。但你的问题是对的@Ralara。我们如何处理多个下划线?

标签: c++ string substring


【解决方案1】:

当第二个下划线始终与最后一个下划线相同时,一个简单的解决方案如下所示:

const auto pos = achRecBuff.find_last_of('_');

const std::string upTo2ndUnderscore = achRecBuff.substr(0, pos);

编辑:考虑到一般情况(感谢@chris 指出),这个 sn-p 也可以满足您的需求:

template <class Container, class Element>
Container beforeNthMatch(const Container& c, const Element& value, unsigned n)
{
    using std::cbegin;
    using std::cend;
    auto pos = cbegin(c);

    while (n-- != 0) {
        pos = std::find(++pos, cend(c), value);

        if (pos == cend(c))
            return {};
    }

    return {cbegin(c), pos};
}

在你的情况下,调用看起来像

const std::string upTo2ndUnderscore = beforeNthMatch(achRecBuff, '_', 2);

像空输入容器这样的情况都被覆盖了,您也可以将它与不同的容器一起使用,例如在std::vector&lt;int&gt; 中找到第 n 个给定整数。

【讨论】:

  • 鉴于 OP 说的是第二个而不是最后一个,我认为这不是他们想要的。
  • 但是在这种情况下,第二个下划线是最后一个下划线。
  • 这个案例是一个例子。 “一些字符串”可以包含下划线似乎是合理的。
  • 是的,就我而言,第二个是最后一个。
【解决方案2】:

您可以像这样多次使用std::string::find:

std::string extract_special_part(std::string const& s)
{
    if(auto pos = s.find('_') + 1)
        if((pos = s.find('_', pos)) + 1)
            return s.substr(0, pos);

    return {};
}

int main()
{
    std::string achRecBuff = "usbaudio_1_req:some string";

    std::cout << extract_special_part(achRecBuff) << '\n';
}

输出:

usbaudio_1

它依赖于std::string::npos 的明确定义的行为,以便在您向其添加一时环绕为零。如果未找到该字符,则if() 语句将失败,因为std::string::npos + 1 变为0,即false。

【讨论】:

    【解决方案3】:
    #include <iostream>
    int main() {
            std::string a="usbaudio_1_req:some string" ;
            std::string::size_type f = a.find("_") ; // find 1st pos
            if ( f!=std::string::npos ) {
                    f=a.find("_", f+1) ;    // find 2nd pos
                    if ( f!=std::string::npos ) {
                            std::string b = a.substr(0, f) ;
                            std::cout << b << std::endl ;
                    }
            }
            return 0 ;
    }
    

    输出是

    usbaudio_1
    

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2018-02-05
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多