C++分割字符串

给定一个字符串和分界符,将分割后的字符串存放在数组中。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    auto split = [](const string& s, char delim)-> vector<string>{
        vector<string> ans;
        string cur;
        for(char ch : s){
            if(ch == delim){
                if(!cur.empty()){
                    ans.push_back(move(cur));
                    cur.clear();
                }

            }else{
                cur += ch;
            }
        }

        if(!cur.empty()){
           ans.push_back(move(cur));
        }

        return ans;
    };

    // 测试用例1
    //string str = "/a/./b/../..//c/";
    //char delim = '/';
    // 测试用例2
    //string str = "/a/./b/../../c/";
    //char delim = '/';
    // 测试用例3
    //string str = "I love you";
    //char delim = ' ';
    // 测试用例4
    string str = "I        love you";
    char delim = ' ';

    vector<string> res = split(str, delim);// 注意,连续出现相同的定界符视为一次分割

    // 打印结果
    cout << "res size = " << res.size() << endl;
    for(string &name : res){
        cout << name << endl;
    }

    return 0;
}

上一篇:python 笔记:dtw包


下一篇:ROS2的C++包