简体   繁体   English

从字符串中提取整数

[英]Extract integer from a string

我有一个类似“ yx-name”的字符串,其中y和x是从0到100的数字。从此字符串中,将c提取为整数变量的最佳方法是什么?

You could split the string by . 您可以将字符串分割为. and convert it to integer type directly. 并将其直接转换为整数类型。 The second number in while loop is the one you want, see sample code: while循环中的第二个数字是您想要的数字,请参见示例代码:

template<typename T>
T stringToDecimal(const string& s)
{
    T t = T();
    std::stringstream ss(s);
    ss >> t;
    return t;
}

int func()
{     
    string s("100.3-name");

    std::vector<int> v;
    std::stringstream ss(s);
    string line;

    while(std::getline(ss, line, '.'))
    {
         v.push_back(stringToDecimal<int>(line));
    }

    std::cout << v.back() << std::endl;

}

It will output: 3 它将输出:3

It seem that this thread has a problem similar to you, it might help ;) 似乎该线程有一个与您类似的问题,可能有帮助;)

Simple string parsing with C++ 使用C ++进行简单的字符串解析

Use two calls to unsigned long strtoul( const char *str, char **str_end, int base ) , eg: 使用两个调用来对unsigned long strtoul( const char *str, char **str_end, int base ) ,例如:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(){

    char const * s = "1.99-name";
    char *endp;
    unsigned long l1 = strtoul(s,&endp,10);
    if (endp == s || *endp != '.') {
        cerr << "Bad parse" << endl;
        return EXIT_FAILURE;
    }
    s = endp + 1;
    unsigned long l2 = strtoul(s,&endp,10);
    if (endp == s || *endp != '-') {
        cerr << "Bad parse" << endl;
        return EXIT_FAILURE;
    }
    cout << "num 1 = " << l1 << "; num 2 = " << l2 << endl;
    return EXIT_FAILURE;
}

You can achieve it with boost::lexical_cast , which utilizes streams like in billz' answer: Pseudo code would look like this (indices might be wrong in that example): 您可以使用boost :: lexical_cast来实现它,它利用像Billz的答案中那样的流:伪代码看起来像这样(该示例中的索引可能是错误的):

std::string yxString = "56.74-name";
size_t xStart = yxString.find(".") + 1;
size_t xLength = yxString.find("-") - xStart;
int x = boost::lexical_cast<int>( yxString + xStart, xLength );

Parsing errors can be handled via exceptions that are thrown by lexical_cast. 可以通过lexical_cast引发的异常来处理解析错误。 For more flexible / powerful text matching I suggest boost::regex . 为了更灵活/更强大的文本匹配,我建议使用boost :: regex

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

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