c++ split的两种实现

本文介绍两种不同的字符串拆分方法:一种是通过索引实现,另一种是利用迭代器实现。这两种方法均能有效地将字符串按空白符拆分成多个子串,并存储到字符串向量中。文章提供了完整的代码示例,包括必要的头文件引入和命名空间使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <string>
#include <iomanip>

using namespace std;
//索引实现
vector<string> split(const string &str)
{
    vector<string> ret;
    int start = 0, end = 0;

    while (end < str.size())
    {//非空字符一直走
        while (end < str.size() && str[end] != ' ')
            end++;
        //截取
        if (start < end)
        {
            ret.push_back(str.substr(start, end - start));
            start = end;
        }
        //跳过连续空格
        while (end < str.size() && str[end] == ' ')
        {
            end++;
            start = end;
        }
    }
    return ret;
}
//迭代器实现
bool is_space(char ch)
{
    return ch == ' ';
}
bool not_space(char ch)
{
    return ch != ' ';
}

vector<string> split_iter(const string & str)
{
    vector<string> ret;
    string::const_iterator start, end;
    start = end = str.begin();

    while (end != str.end())
    {
        //先查找空格
        start = find_if(start, str.end(), not_space);
        end = start;
        //找到单词结尾
        end = find_if(start, str.end(), is_space);

        //截取
        if (start != end)
        {
            ret.push_back(string(start, end));
            start = end;
        }
    }
    return ret;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值