Parse (split) a string in C++ using string delimiter (standard C++)

This question already has an answer here:

  • The most elegant way to iterate the words of a string [closed] 74 answers

  • You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token.

    Example:

    std::string s = "scott>=tiger";
    std::string delimiter = ">=";
    std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
    
  • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.

  • The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos .


  • If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length()); ):

    s.erase(0, s.find(delimiter) + delimiter.length());
    

    This way you can easily loop to get each token.

    Complete Example

    std::string s = "scott>=tiger>=mushroom";
    std::string delimiter = ">=";
    
    size_t pos = 0;
    std::string token;
    while ((pos = s.find(delimiter)) != std::string::npos) {
        token = s.substr(0, pos);
        std::cout << token << std::endl;
        s.erase(0, pos + delimiter.length());
    }
    std::cout << s << std::endl;
    

    Output:

    scott
    tiger
    mushroom
    

    该方法使用std::string::find而不用通过记住前一个子串标记的开始和结束来改变原始字符串。

    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string s = "scott>=tiger";
        std::string delim = ">=";
    
        auto start = 0U;
        auto end = s.find(delim);
        while (end != std::string::npos)
        {
            std::cout << s.substr(start, end - start) << std::endl;
            start = end + delim.length();
            end = s.find(delim, start);
        }
    
        std::cout << s.substr(start, end);
    }
    

    你可以使用下一个函数来拆分字符串:

    vector<string> split(const string& str, const string& delim)
    {
        vector<string> tokens;
        size_t prev = 0, pos = 0;
        do
        {
            pos = str.find(delim, prev);
            if (pos == string::npos) pos = str.length();
            string token = str.substr(prev, pos-prev);
            if (!token.empty()) tokens.push_back(token);
            prev = pos + delim.length();
        }
        while (pos < str.length() && prev < str.length());
        return tokens;
    }
    
    链接地址: http://www.djcxy.com/p/19560.html

    上一篇: 使用标记分割C ++ std :: string,例如“;”

    下一篇: 使用字符串分隔符(标准C ++)在C ++中解析(拆分)字符串