我有一个字符串,例如
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的,在网上找不到答案
非常感谢您的帮助!
答案 0 :(得分:1)
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,用于搜索字符串中的模式。
答案 1 :(得分:0)
这是基于精神的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;
}