首页 文章

使用字符串分隔符(标准C)在C中解析(拆分)字符串[重复]

提问于
浏览
219

这个问题在这里已有答案:

我使用以下代码在C中解析字符串:

string parsed,input="text to be parsed";
stringstream input_stringstream(input);

if(getline(input_stringstream,parsed,' '))
{
     // do some processing.
}

使用单个char分隔符进行解析很好 . 但是,如果我想使用字符串作为分隔符,该怎么办?

示例:我想拆分:

scott>=tiger

用> =作为分隔符,这样我就能得到斯科特和老虎 .

11 回答

  • 13

    您可以使用std::string::find()函数查找字符串分隔符的位置,然后使用std::string::substr()获取令牌 .

    例:

    std::string s = "scott>=tiger";
    std::string delimiter = ">=";
    std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
    
    • find(const string& str, size_t pos = 0) 函数返回字符串中第一次出现的 str 的位置,如果找不到该字符串,则返回npos .

    • substr(size_t pos = 0, size_t n = npos) 函数返回对象的子字符串,从位置 pos 开始,长度为 npos .


    如果您有多个分隔符,则在提取一个标记后,可以将其删除(包括分隔符)以继续进行后续提取(如果要保留原始字符串,只需使用 s = s.substr(pos + delimiter.length()); ):

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

    这样您就可以轻松循环获取每个令牌 .

    完整示例

    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;
    

    输出:

    scott
    tiger
    mushroom
    
  • 1

    此方法使用 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);
    }
    
  • 4

    您可以使用next函数来拆分字符串:

    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;
    }
    
  • 25

    strtok允许您传递多个字符作为分隔符 . 我打赌如果你传入">="你的示例字符串将被正确分割(即使>和=被计为单独的分隔符) .

    编辑如果您不想使用 c_str() 将字符串转换为字符*,则可以使用substrfind_first_of进行标记 .

    string token, mystring("scott>=tiger");
    while(token != mystring){
      token = mystring.substr(0,mystring.find_first_of(">="));
      mystring = mystring.substr(mystring.find_first_of(">=") + 1);
      printf("%s ",token.c_str());
    }
    
  • 384

    此代码从文本中分割行,并将所有人添加到矢量中 .

    vector<string> split(char *phrase, string delimiter){
        vector<string> list;
        string s = string(phrase);
        size_t pos = 0;
        string token;
        while ((pos = s.find(delimiter)) != string::npos) {
            token = s.substr(0, pos);
            list.push_back(token);
            s.erase(0, pos + delimiter.length());
        }
        list.push_back(s);
        return list;
    }
    

    被称为:

    vector<string> listFilesMax = split(buffer, "\n");
    
  • 0

    用于字符串分隔符

    基于字符串分隔符拆分字符串 . 如基于字符串分隔符 "-+" 拆分字符串 "adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih" ,输出将为 {"adsf", "qwret", "nvfkbdsj", "orthdfjgh", "dfjrleih"}

    #include <iostream>
    #include <sstream>
    #include <vector>
    
    using namespace std;
    
    // for string delimiter
    vector<string> split (string s, string delimiter) {
        size_t pos_start = 0, pos_end, delim_len = delimiter.length();
        string token;
        vector<string> res;
    
        while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
            token = s.substr (pos_start, pos_end - pos_start);
            pos_start = pos_end + delim_len;
            res.push_back (token);
        }
    
        res.push_back (s.substr (pos_start));
        return res;
    }
    
    int main() {
        string str = "adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih";
        string delimiter = "-+";
        vector<string> v = split (str, delimiter);
    
        for (auto i : v) cout << i << endl;
    
        return 0;
    }
    

    Output

    adsf
    qwret
    nvfkbdsj
    orthdfjgh
    dfjrleih
    

    对于单字符分隔符

    基于字符分隔符拆分字符串 . 如分割字符串 "adsf+qwer+poui+fdgh" 与分隔符 "+" 将输出 {"adsf", "qwer", "poui", "fdg"h}

    #include <iostream>
    #include <sstream>
    #include <vector>
    
    using namespace std;
    
    vector<string> split (const string &s, char delim) {
        vector<string> result;
        stringstream ss (s);
        string item;
    
        while (getline (ss, item, delim)) {
            result.push_back (item);
        }
    
        return result;
    }
    
    int main() {
        string str = "adsf+qwer+poui+fdgh";
        vector<string> v = split (str, '+');
    
        for (auto i : v) cout << i << endl;
    
        return 0;
    }
    

    Output

    adsf
    qwer
    poui
    fdgh
    
  • -3

    我会用 boost::tokenizer . 这里是解释如何制作适当的标记化函数的文档:http://www.boost.org/doc/libs/1_52_0/libs/tokenizer/tokenizerfunction.htm

    这是适用于您的情况的一个 .

    struct my_tokenizer_func
    {
        template<typename It>
        bool operator()(It& next, It end, std::string & tok)
        {
            if (next == end)
                return false;
            char const * del = ">=";
            auto pos = std::search(next, end, del, del + 2);
            tok.assign(next, pos);
            next = pos;
            if (next != end)
                std::advance(next, 2);
            return true;
        }
    
        void reset() {}
    };
    
    int main()
    {
        std::string to_be_parsed = "1) one>=2) two>=3) three>=4) four";
        for (auto i : boost::tokenizer<my_tokenizer_func>(to_be_parsed))
            std::cout << i << '\n';
    }
    
  • 6

    这是我对此的看法 . 它处理边缘情况并采用可选参数从结果中删除空条目 .

    bool endsWith(const std::string& s, const std::string& suffix)
    {
        return s.size() >= suffix.size() &&
               s.substr(s.size() - suffix.size()) == suffix;
    }
    
    std::vector<std::string> split(const std::string& s, const std::string& delimiter, const bool& removeEmptyEntries = false)
    {
        std::vector<std::string> tokens;
    
        for (size_t start = 0, end; start < s.length(); start = end + delimiter.length())
        {
             size_t position = s.find(delimiter, start);
             end = position != string::npos ? position : s.length();
    
             std::string token = s.substr(start, end - start);
             if (!removeEmptyEntries || !token.empty())
             {
                 tokens.push_back(token);
             }
        }
    
        if (!removeEmptyEntries &&
            (s.empty() || endsWith(s, delimiter)))
        {
            tokens.push_back("");
        }
    
        return tokens;
    }
    

    例子

    split("a-b-c", "-"); // [3]("a","b","c")
    
    split("a--c", "-"); // [3]("a","","c")
    
    split("-b-", "-"); // [3]("","b","")
    
    split("--c--", "-"); // [5]("","","c","","")
    
    split("--c--", "-", true); // [1]("c")
    
    split("a", "-"); // [1]("a")
    
    split("", "-"); // [1]("")
    
    split("", "-", true); // [0]()
    
  • 39

    如果你不想修改字符串(如Vincenzo Pii的答案) and 也希望输出最后一个标记,你可能想要使用这种方法:

    inline std::vector<std::string> splitString( const std::string &s, const std::string &delimiter ){
        std::vector<std::string> ret;
        size_t start = 0;
        size_t end = 0;
        size_t len = 0;
        std::string token;
        do{ end = s.find(delimiter,start); 
            len = end - start;
            token = s.substr(start, len);
            ret.emplace_back( token );
            start += len + delimiter.length();
            std::cout << token << std::endl;
        }while ( end != std::string::npos );
        return ret;
    }
    
  • 7
    #include<iostream>
    #include<algorithm>
    using namespace std;
    
    int split_count(string str,char delimit){
    return count(str.begin(),str.end(),delimit);
    }
    
    void split(string str,char delimit,string res[]){
    int a=0,i=0;
    while(a<str.size()){
    res[i]=str.substr(a,str.find(delimit));
    a+=res[i].size()+1;
    i++;
    }
    }
    
    int main(){
    
    string a="abc.xyz.mno.def";
    int x=split_count(a,'.')+1;
    string res[x];
    split(a,'.',res);
    
    for(int i=0;i<x;i++)
    cout<<res[i]<<endl;
      return 0;
    }
    

    P.S:仅当分裂后字符串的长度相等时才有效

  • 3
    std::vector<std::string> split(const std::string& s, char c) {
      std::vector<std::string> v;
      unsigned int ii = 0;
      unsigned int j = s.find(c);
      while (j < s.length()) {
        v.push_back(s.substr(i, j - i));
        i = ++j;
        j = s.find(c, j);
        if (j >= s.length()) {
          v.push_back(s.substr(i, s,length()));
          break;
        }
      }
      return v;
    }
    

相关问题