在C++中,我們有時候需要拆分字符串,比如字符串string str = "dog cat cat dog"想以空格區分拆成四個單詞,Java中實在太方便了,直接String[] v = str.split(" ");就搞定了,而c++中沒有這么方便的實現,但也有很多的方法能實現這個功能,下面列出五種常用的實現的方法,請根據需要選擇,個人覺得前三種使用起來比較方便,參見代碼如下:
#include <vector> #include <iostream> #include <string> #include <sstream> string str = "dog cat cat dog"; istringstream in(str); vector<string> v; // Method 1 string t; while (in >> t) { v.push_back(t); }
// Method 2 // #include <iterator> copy(istream_iterator<string>(in), istream_iterator<string>(), back_inserter(v));
// Method 3 string t; while (getline(in, t, ' ')) { v.push_back(t); }
// Method 4 string str2 = str; while (str2.find(" ") != string::npos) { int found = str2.find(" "); v.push_back(str2.substr(0, found)); str2 = str2.substr(found + 1); } v.push_back(str2);
// Method 5 // #include <stdio.h> // #include <stdlib.h> // #include <string.h> char *dup = strdup(str.c_str()); char *token = strtok(dup, " "); while (token != NULL) { v.push_back(string(token)); token = strtok(NULL, " "); } free(dup);