如何用C ++解析复杂的字符串? [英] How to parse complex string with C++?

查看:141
本文介绍了如何用C ++解析复杂的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何使用"sstream"和C ++解析此字符串

I'm trying to figure out how could I parse this string using "sstream" and C++

其格式为:字符串,整数,整数".

The format of it is: "string,int,int".

我需要能够将包含IP地址的字符串的第一部分分配给std :: string.

I need to be able to assign the first part of the string which contains an IP address to a std::string.

以下是此字符串的示例:

Here is an example of this string:

std::string("127.0.0.1,12,324");

然后我需要获取

string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;

我会再次提到我不能使用boost库,只能使用sstream :-)

I will mention again that I can't use boost library, just sstream :-)

谢谢

推荐答案

这是一个有用的标记化功能.它不使用流,但是可以通过在逗号上分割字符串来轻松地执行您所需的任务.然后,您可以对令牌的结果向量做任何您想做的事情.

Here's a useful tokenization function. It doesn't use streams, but can easily perform the task you require by splitting the string on commas. Then you can do whatever you want with the resulting vector of tokens.

/// String tokenizer.
///
/// A simple tokenizer - extracts a vector of tokens from a 
/// string, delimited by any character in delims.
///
vector<string> tokenize(const string& str, const string& delims)
{
    string::size_type start_index, end_index;
    vector<string> ret;

    // Skip leading delimiters, to get to the first token
    start_index = str.find_first_not_of(delims);

    // While found a beginning of a new token
    //
    while (start_index != string::npos)
    {
        // Find the end of this token
        end_index = str.find_first_of(delims, start_index);

        // If this is the end of the string
        if (end_index == string::npos)
            end_index = str.length();

        ret.push_back(str.substr(start_index, end_index - start_index));

        // Find beginning of the next token
        start_index = str.find_first_not_of(delims, end_index);
    }

    return ret;
}

这篇关于如何用C ++解析复杂的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆