如何在c ++中搜索std :: string中的子字符串? [英] How do you search a std::string for a substring in C++?

查看:1791
本文介绍了如何在c ++中搜索std :: string中的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中解析一个简单的字符串。我知道字符串包含一些带冒号的文本,后面紧跟一个空格,然后一个数字。我想提取字符串的数字部分。我不能只在空格上使用符号化(使用sstream和<<),因为冒号前面的文本可以有也可以没有空格。

I'm trying to parse a simple string in C++. I know the string contains some text with a colon, followed immediately by a space, then a number. I'd like to extract just the number part of the string. I can't just tokenize on the space (using sstream and <<) because the text in front of the colon may or may not have spaces in it.

一些示例字符串可能是:

Some example strings might be:


总磁盘空间:9852465

Total disk space: 9852465

空格:6243863

Free disk space: 6243863

部门:4095

我想使用标准库,但如果你有另一个解决方案,你也可以发布,因为其他人有相同的问题可能想看到不同的解决方案。

I'd like to use the standard library, but if you have another solution you can post that too, since others with the same question might like to see different solutions.

推荐答案

std::string strInput = "Total disk space: 9852465";
std::string strNumber = "0";
size_t iIndex = strInput.rfind(": ");
if(iIndex != std::string::npos && strInput.length() >= 2)
{
  strNumber = strInput.substr(iIndex + 2, strInput.length() - iIndex - 2)
}

这篇关于如何在c ++中搜索std :: string中的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆