基于其中的数字子字符串拆分字符串

split string based on numeric substrings inside it

本文关键字:字符串 拆分 数字 于其中      更新时间:2023-10-16

我有一个字符串,例如

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个char长

我找到了一个类似的问题,但适用于JS,我找不到搜索网络的答案

预先感谢您的任何帮助!

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及以后有一个本机正则表达式库,以搜索字符串中的模式。

,这是基于精神的解决方案:

#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;
}