好吗?字符串我的意思是std :: string
这是我使用的perl风格的分割功能:
void split(const string& str, const string& delimiters , vector& tokens) { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } }
在C++中没有内置的方法来分割字符串,但是boost提供字符串算法库来执行所有类型的字符串操作,包括字符串拆分.
是的,串流.
std::istringstream oss(std::string("This is a test string")); std::string word; while(oss >> word) { std::cout << "[" << word << "] "; }
STL字符串
您可以使用字符串迭代器来完成您的脏工作.
std::string str = "hello world"; std::string::const_iterator pos = std::find(string.begin(), string.end(), ' '); // Split at ' '. std::string left(str.begin(), pos); std::string right(pos + 1, str.end()); // Echoes "hello|world". std::cout << left << "|" << right << std::endl;