C++ split string via delimeter

复制代码
#pragma once 
#pragma comment(lib,"rpcrt4.lib")

#include <Windows.h>
#include <rpcdce.h>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void stringDemo()
{
    string str = "Hello world";
    string str2 = str.substr(12);
    cout << str << endl << str2 << endl;
}

string getUuid()
{
    RPC_CSTR rpcStr;
    string uuidValue;
    UUID newUUID;
    UuidCreate(&newUUID);
    UuidToStringA(&newUUID, &rpcStr);
    uuidValue = (char*)rpcStr;
    RpcStringFreeA(&rpcStr);
    return uuidValue;
}

void splitString(string str, string delimeter)
{
    size_t pos = 0;
    string tempStr;
    while ((pos = str.find(delimeter)) != string::npos)
    {
        tempStr = str.substr(0, pos);
        cout << tempStr << endl;
        str.erase(0, pos + delimeter.length());
    }
    cout << str << endl;
}

void splitUuid()
{
    string uuidStr = getUuid();
    cout << uuidStr << endl;
    string delimeter = "-";
    splitString(uuidStr, delimeter);
}

void splitStringToVector(vector<string> &vec, string sourceStr, string delimeter)
{
    size_t pos = 0;
    string tempStr;
    while ((pos = sourceStr.find(delimeter)) != string::npos)
    {
        tempStr = sourceStr.substr(0, pos);
        vec.push_back(tempStr); 
        sourceStr.erase(0, pos + delimeter.length());
    }
    vec.push_back(sourceStr);
}

void stringSplitDemo()
{
    string sourceStr = getUuid();
    cout << sourceStr << endl;
    string delimeter = "-";
    vector<string> vec;
    splitStringToVector(std::ref(vec), sourceStr, delimeter);
    vector<string>::iterator itr = vec.begin();
    cout << "Split:" << endl;
    while (itr != vec.end())
    {
        cout << *itr << endl;
        itr++;
    }
}

int main()
{
    try
    {
        stringSplitDemo();
    }
    catch (const std::exception&ex)
    {
        cout << ex.what() << endl;
    }
}
复制代码

 

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