美文网首页
c++ 字符串分割处理

c++ 字符串分割处理

作者: 何亮hook_8285 | 来源:发表于2022-11-17 22:02 被阅读0次

    第一种方式

    #include <string>
    #include <vector>
    #include <sstream>
    #include <iostream>
    
    int main() {
        std::string name="zhangsan;lisi;zhangsan123";
        std::istringstream  iss(name);
        std::string token;
        std::vector<std::string> strlist;
        while(std::getline(iss,token,';'))
        {
                std::cout << token << std::endl;
                strlist.push_back(token);
    
        }
    
        std::cout << strlist.size() << std::endl;
        return 0;
    }
    

    第二种方式

    #include <iostream>
    #include <string>
    
    int main() {
        std::string name="zhangsan;lisi;zhangsan123";
        //在字符串末尾也加入分隔符,方便截取最后一段
        const char split=';';
        std::string strs = name + split;
        size_t pos=strs.find(split);
        while(pos!=strs.npos)
        {
            std::string temp=strs.substr(0,pos);
            std::cout << temp << std::endl;
            //去掉已分割的字符串,在剩下的字符串中进行分割
            strs = strs.substr(pos + 1, strs.size());
            pos = strs.find(split);
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:c++ 字符串分割处理

          本文链接:https://www.haomeiwen.com/subject/qbjuxdtx.html