用stringstream可以用指定字符分割字符串:

默认分割空格、tab、回车换行

#include <iostream>
#include <sstream>
#include <vector>
 
using namespace std;
 
int main() {
    string str = "hello world sperated by   spaces\tand\nhuiche";
 
    vector<string> arr;
    istringstream ss(str);
    string word;
    while(ss>>word) {
        arr.push_back(word);
    }
 
    for(size_t i=0; i<arr.size(); i++) {
        cout << arr[i] << endl;
    }
     
    return 0;
}

利用指定字符分割字符串

#include <iostream>
#include <sstream>
#include <vector>
 
using namespace std;
 
int main() {
        std::string data = "1_2_3_4_5_6";
        std::stringstream ss(data);
        std::string item;
        queue<string> q;
        cout << data << endl;
        while (std::getline(ss, item, '_')) 
            cout << item << ' ';  
}

//1_2_3_4_5_6
//1 2 3 4 5 6 


posted @   narjaja  阅读(8148)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
· 程序员转型AI:行业分析
点击右上角即可分享
微信分享提示