C ++从字符串的中间提取数字 [英] C++ Extract number from the middle of a string

查看:616
本文介绍了C ++从字符串的中间提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量包含 strings ,格式为 text_number-number

I have a vector containing strings that follow the format of text_number-number

例如: Example_45-3

我只想要第一个数字(在例子中 45 ),没有其他我可以用我目前的代码:

I only want the first number (45 in the example) and nothing else which I am able to do with my current code:

std::vector<std::string> imgNumStrVec;
for(size_t i = 0; i < StrVec.size(); i++){
    std::vector<std::string> seglist;
    std::stringstream ss(StrVec[i]);
    std::string seg, seg2;
    while(std::getline(ss, seg, '_')) seglist.push_back(seg);
    std::stringstream ss2(seglist[1]);
    std::getline(ss2, seg2, '-');
    imgNumStrVec.push_back(seg2); 
}

有更简化和更简单的方法吗?如果是这样,他们是什么?

Are there more streamlined and simpler ways of doing this? and if so what are they?

我纯粹是出于渴望学习如何更好地编码,因为在一天结束,上面的代码成功提取只是

I ask purely out of desire to learn how to code better as at the end of the day, the code above does successfully extract just the first number, but it seems long winded and round-about.

推荐答案

适用于许多字符串(不仅仅是字符串)的最小实现示例text_45-text:

Minimal implementation example that works on many strings (not just strings of the form "text_45-text":

string s = boost::regex_replace(
    string("Example_45-3"),
    boost::regex("[^0-9]*([0-9]+).*"),
    string("\\1")
    );

这将工作的其他示例字符串:

Other example strings that this would work on:


  • asdfasdf 45 sdfsdf

  • X = 45,sdfsdf

对于这个例子,我在Linux上使用了 #include< boost / regex.hpp>

For this example I used g++ on Linux with #include <boost/regex.hpp> and -lboost_regex. You could also use C++11x regex.

如果你有一个更好的正则表达式,随意编辑我的解决方案。

Feel free to edit my solution if you have a better regex.

注释:

如果没有性能限制,是理想的这种事情,因为你不是重新发明轮子(通过编写一串字符串解析代码,需要时间写/测试)。

If there aren't performance constraints, using Regex is ideal for this sort of thing because you aren't reinventing the wheel (by writing a bunch of string parsing code which takes time to write/test-fully).

此外,如果/当你的字符串变得更复杂或更多样式regex容易适应复杂性。 (问题的示例模式很容易,但通常一个更复杂的模式需要10-100 +行代码,当一行正则表达式也会这样做)。

Additionally if/when your strings become more complex or have more varied patterns regex easily accommodates the complexity. (The question's example pattern is easy enough. But often times a more complex pattern would take 10-100+ lines of code when a one line regex would do the same.)

这篇关于C ++从字符串的中间提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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