【问题标题】:split string based on numeric substrings inside it根据其中的数字子字符串拆分字符串
【发布时间】:2019-11-16 23:00:18
【问题描述】:

我有一个字符串,例如

std::string input = "Trp80Ter";

我需要将其拆分取数值前后的字母,得到:

std::string substring0 = "Trp";
std::string substring1 = "Ter";
int number = 80;

此外,它应该是字符串中出现的第一个数字,因为我的值也可以是:

std::string input = "Arg305LeufsTer18";

// which I need to transform in:
std::string substring0 = "Arg";
std::string substring1 = "LeufsTer18";
int number = 305;

PS:字符串的第一个“字符”部分并不总是 3 个字符长

我找到了一个similar question,但它是针对 JS 的,我在网上找不到答案

非常感谢您的任何帮助!

【问题讨论】:

    标签: c++ string split substring


    【解决方案1】:

    这是一个基于精神的solution

    #include <string>
    #include <iostream>
    #include <boost/fusion/adapted/std_tuple.hpp>
    #include <boost/spirit/home/x3.hpp>
    
    int main() {
        std::string input = "Arg305LeufsTer18";
        using namespace boost::spirit::x3;
        const auto first_str = +char_("A-Za-z");
        const auto second_str = +char_("A-Za-z0-9");
        std::tuple<std::string, int, std::string> out;
        parse(input.begin(), input.end(), first_str >> int_ >> second_str, out);
    
        std::cout << get<0>(out) << std::endl << get<1>(out) << std::endl << get<2>(out) << std::endl;
    }
    

    【讨论】:

      【解决方案2】:
      std::string input = "...";
      std::string::size_type pos1 = input.find_first_of("0123456789");
      std::string::size_type pos2 = input.find_first_not_of("0123456789", pos1);
      std::string substring0 = input.substr(0, pos1);
      std::string substring1 = input.substr(pos2);
      int number = std::stoi(input.substr(pos1, pos2-pos1));
      

      或者,C++11 及更高版本有一个本机 Regular Expression library 用于搜索字符串中的模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-11
        相关资源
        最近更新 更多