C++ 字符串分割函数

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
using namespace std;

void Myprint(string s)
{
    cout<<s<<endl;
}

vector<string> Split(string s,string c)
{
    vector<string> arr;
    string str_t;
    int num=0;
    do
    {
        num = s.find(c);
        if(num==-1)
        {
            break;
        }      
        str_t=s.substr(0,num);
        arr.push_back(str_t);
        s.erase(0,num+1);
    } while (true);   
    arr.push_back(s);
    return arr;
}

int main()
{
    string str = "abc 123 def";
    auto beforetime = chrono::steady_clock::now();
    vector<string> arr = Split(str," ");
    auto aftertime = chrono::steady_clock::now();
    for_each(arr.begin(),arr.end(),Myprint);
    double ms = chrono::duration<double,milli>(aftertime-beforetime).count();
    cout<<"运行时间"<<ms<<endl;
    system("pause");
}

abc
123
def
运行时间0.0235
请按任意键继续. . .

posted @   cjjloveslife  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示