简体   繁体   English

在 C++ 中,我应该如何解析嵌套在字符串中的整数,其中整数是可变长度的?

[英]In C++, how should I go about parsing an integer nested within a string, where the integer is of variable length?

The text to the left and right of the integer is relevant to initialize an object, so it needs to be kept.整数左右两侧的文本与初始化对象有关,因此需要保留。 The starting of the integer will persist and i'm thinking I will try and use a while loop to check to see if the next character is also digit, but I feel like their must be a more elegant solution.整数的开头将持续存在,我想我会尝试使用 while 循环来检查下一个字符是否也是数字,但我觉得它们必须是一个更优雅的解决方案。 Does anyone have any hints, tips, or tricks?有没有人有任何提示、技巧或窍门?

Instead of writing a while loop to convert a sequence of charachers to an integer value, the standard library provides std::istringstream and formatted input ( operator>>() as illustrated by this simple example:标准库没有编写 while 循环来将字符序列转换为整数值, std::istringstream提供std::istringstream和格式化输入( operator>>()如下面的简单示例所示:

void example1()
{
    std::string s{"Hello 1234 World\n"};

    std::istringstream ss(s.substr(6,std::string::npos));

    int nbr;
    ss >> nbr;

    std::cout << "The number is " << nbr << std::endl;
}

In this example, the starting position of the string is known.在这个例子中,字符串的起始位置是已知的。 If not, you would need to either parse the string (which in simple cases can be done using similar techniques).如果没有,您将需要解析字符串(在简单的情况下可以使用类似的技术来完成)。 For instance, if the number is preceeded by the string "Nbr:", you can use string::find例如,如果数字前面是字符串“Nbr:”,则可以使用string::find

void example2()
{
    std::string s{"Some uninteresting text... Nbr: 1234 World\n"};

    auto pos = s.find("Nbr:");
    std::istringstream ss(s.substr(pos+4,std::string::npos));

    int nbr;
    ss >> nbr;

    std::cout << "The number is " << nbr << std::endl;
}

Or you can used regex to find the first number in the string and use std::stoi on the submatch:或者您可以使用正则表达式查找字符串中的第一个数字并在子匹配上使用std::stoi

void example3()
{
    std::string s{"Some uninteresting text... : 1234 World\n"};

    std::regex rgx("[^0-9]*(\\d+).*");
    std::smatch match;

    if (std::regex_search(s, match, rgx)) {
        auto n = std::stoi(match[1]);
        std::cout << "the number is " << n << '\n';
    } else {
        std::cout << "no match\n";
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM