Splitting strings in C++
This question already has an answer here:
this works nicely for me :), it puts the results in elems
. delim
can be any char
.
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;
}
有了这个包含Boost的Mingw发行版:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <ostream>
#include <algorithm>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
int main() {
vector<string> v;
split(v, "1=2&3=4&5=6", is_any_of("=&"));
copy(v.begin(), v.end(), ostream_iterator<string>(cout, "n"));
}
Try using stringstream:
std::string line("A line of tokens");
std::stringstream lineStream(line);
std::string token;
while(lineStream >> token)
{
}
Check out my answer to your last question:
C++ Reading file Tokens
上一篇: 将字符串解析为int的向量
下一篇: 在C ++中分割字符串