如何从字符串开头到第二个分隔符中提取子字符串?
How to extract a substring from string beginning to the second delimiter?
我的字符串是: 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
相关文章:
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 如何在字符串中找到字符,然后在C++中提取其余的字符串
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 清除输入缓冲区后未提取字符串流
- 如何创建一个函数来提取向量内部字符串中的字段?
- 从没有空格的字符串中提取整数
- 如何使用正则表达式从字符串中提取值
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 提取字符串中的随机单词
- 将子字符串提取到最后 n 个分隔符C++
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- Arduino中的字符串提取问题
- C++ 在将字符串提取到标量时处理溢出/下溢
- 将两个 '' 字符之间的子字符串提取到单独的数组中
- 字符提取与字符串提取有何不同
- 如何从输入字符串提取数值?c++
- 作为XML字符串提取请求/响应