C++ split() 函数

C++中没有 split() 函数,有时在处理字符串的时候很不方便。

下面我们就来实现一个自己的 split() 函数。

split()
static void _split(const std::string &s, char delim, 
                   std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;

    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    _split(s, delim, elems);
    return elems;
}

我们测试下:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>

int main(void)
{
    std::vector<std::string> x = split("hello,world,c++", ',');
    
    for (auto it = std::begin(x); it != std::end(x); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
}

运行看看效果如何

# g++ -std=c++0x -Wall -g main.cpp
hello world c++


嗯嗯,可以正常工作。
我现在如果想获得分割后指定位置的字符串,比如,上面例子中返回 hello world c++,第0个位置是 hello,第1个位置是 world,第2个位置是 c++,该怎么做呢?


好,我们接着处理:

extract()
// 我将分隔符默认设为空格,当然也可以设为其他字符如','
std::string extract(std::string &values, int index, char delim = ' ') {
    if (values.length() == 0)
        return std::string("");

    std::vector<std::string> x = split(values, delim);
    try {
        return x.at(index);
    } catch(const std::out_of_range& e) {
        return std::string("");  // 要是访问超出范围的元素,我们就返回空串
    }
}

我们再来测试下:
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <string>

int main(void)
{
    std::string str;
    std::string s("How old are you?");
    std::string s2("hello,world,c++");
    std::string s3("one:two:three");
	
    str = extract(s, 1);  // 默认空格分隔
    std::cout << str << std::endl;
    
    for (int i = 0; i < 3; i++) {
        str = extract(s2, i, ',');  // ,分隔
        std::cout << i << "->" << str << std::endl;
    }
    
    str = extract(s2, 5, ',');  // 访问一个超出范围的元素
    std::cout << str << std::endl;
    
    str = extract(s3, 0, ':');  // :分隔
    std::cout << str << std::endl;
}

我们来运行看看

# g++ -std=c++0x -Wall -g main.cpp
old
0->hello
1->world
2->c++

one


OK,打完,收功 ^_^


  • 13
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值