如何从字符串开头到第二个分隔符中提取子字符串?

How to extract a substring from string beginning to the second delimiter?

本文关键字:字符串 提取 分隔符 开头 第二个      更新时间:2023-10-16

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

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

我该怎么做?

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

const auto pos = achRecBuff.find_last_of('_');
const std::string upTo2ndUnderscore = achRecBuff.substr(0, pos);

编辑:考虑到一般情况(感谢@chris指出这一点(,此片段也可以满足您的需求:

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<int>中查找第 n 个给定整数。

你可以像这样使用 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明确定义行为,当您向其添加 1 时,将其四舍五入为零。如果未找到该字符,则if()语句将失败,因为std::string::npos + 1变为0,这是false

#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