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,打完,收功 ^_^