代码之家  ›  专栏  ›  技术社区  ›  Goles

如何用C++解析复杂字符串?

  •  12
  • Goles  · 技术社区  · 16 年前

    我正试图找出如何使用“ sstream

    它的格式是:“string,int,int”。

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

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

    然后我需要获得

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

    boost 图书馆 溪流 :-)

    4 回复  |  直到 16 年前
        1
  •  3
  •   Eli Bendersky    16 年前

    下面是一个有用的标记化函数。它不使用流,但可以通过在逗号上拆分字符串来轻松执行所需的任务。然后,您可以对生成的令牌向量执行任何操作。

    /// 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;
    }
    
        2
  •  13
  •   Matthieu N. Matthieu N.    15 年前

    这个 C++ String Toolkit Library (Strtk) 您的问题有以下解决方案:

    int main()
    {
       std::string data("127.0.0.1,12,324");
       string someString;
       int aNumber;
       int bNumber;
       strtk::parse(data,",",someString,aNumber,bNumber);
       return 0;
    }
    

    Here

        3
  •  6
  •   Ryan    16 年前

    这并不奇怪,但您可以使用std::getline拆分字符串:

    std::string example("127.0.0.1,12,324");
    std::string temp;
    std::vector<std::string> tokens;
    std::istringstream buffer(example);
    
    while (std::getline(buffer, temp, ','))
    {
        tokens.push_back(temp);
    }
    

    然后可以从每个分隔的字符串中提取必要的信息。

        4
  •  2
  •   Goz    16 年前

    我相信你也可以这样做(完全出乎我的意料,如果我犯了一些错误,我向你道歉)。。。

    stringstream myStringStream( "127.0.0.1,12,324" );
    int ipa, ipb, ipc, ipd;
    char ch;
    int aNumber;
    int bNumber;
    myStringStream >> ipa >> ch >> ipb >> ch >> ipc >> ch >> ipd >> ch >> aNumber >> ch >> bNumber;
    
    stringstream someStringStream;
    someStringStream << ipa << "." << ipb << "." << ipc << "." << ipd;
    string someString( someStringStream.str() );
    
    推荐文章