用标准库或者boost分割C++字符串

阅读更多

使用标准库

#include 
#include 
#include 
#include 
using namespace std;

std::vector &split(const std::string &s, char delim, std::vector &elems) {
	std::stringstream ss(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		if (!item.empty()){
			elems.push_back(item);
		}
	}
	return elems;
}

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

int main(){
	string s = "string	to	split a";
	vector columns = split(s, '\t');
	for (vector::iterator it = columns.begin(); it != columns.end(); it++){
		cout << *it << endl;
	}
	return 0;
}

 

 

使用boost 

#include 
#include 
#include 
#include 
using namespace std;

int main(){
	string s = "string	to	split a";
	vector strs;
	boost::split(strs, s , boost::is_any_of("\t"));
	for (vector::iterator it = strs.begin(); it != strs.end(); it++){
		cout << *it << endl;
	}
	return 0;
}

 

你可能感兴趣的:(用标准库或者boost分割C++字符串)