Split a string into an array in C++
Possible Duplicate:
How to split a string in C++?
I have an input file of data and each line is an entry. in each line each "field" is seperated by a white space " " so I need to split the line by space. other languages have a function called split (C#, PHP etc) but I cant find one for C++. How can I achieve this? Here is my code that gets the lines:
string line;
ifstream in(file);
while(getline(in, line)){
// Here I would like to split each line and put them into an array
}
#include <sstream> //for std::istringstream
#include <iterator> //for std::istream_iterator
#include <vector> //for std::vector
while(std::getline(in, line))
{
std::istringstream ss(line);
std::istream_iterator<std::string> begin(ss), end;
//putting all the tokens in the vector
std::vector<std::string> arrayTokens(begin, end);
//arrayTokens is containing all the tokens - use it!
}
By the way, use qualified-names such as std::getline
, std::ifstream
like I did. It seems you've written using namespace std
somewhere in your code which is considered a bad practice. So don't do that:
vector<string> v;
boost::split(v, line, ::isspace);
http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768
I have written a function for a simlar requirement of mine. may be u can use it!
std::vector<std::string> &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);
}
return elems;
}
链接地址: http://www.djcxy.com/p/19566.html
上一篇: 在PHP的explode()函数的C ++中是否有等价物?
下一篇: 用C ++将一个字符串拆分成一个数组