■
しーぷらぷらの練習した。任意の区切り文字で文字列を分割してvectorに入れる。
#include <iostream> #include <string> #include <vector> using namespace std; vector<string> split(string str, string delims){ vector<string> result; int begin = -1; int end = str.find_first_of(delims); while(end != str.npos){ result.push_back(str.substr(begin+1, end-begin-1)); begin = end; end = str.find_first_of(delims, begin+1); } result.push_back(str.substr(begin+1)); return result; } void test(string str, string delims){ cout << "string: \"" << str << "\"" << endl; cout << "delims: \"" << delims << "\"" << endl; cout << "result: "; vector<string> v = split(str, delims); for(int i = 0; i < v.size(); i++){ cout << "\"" << v[i] << "\" "; } cout << "\n--------" << endl; } int main() { test("a b c d e", " "); test("a,b,c,d,e", ","); test("a b,c d,e", " ,"); test("a|b,c&d(e", "|,&("); test("abcde", " "); return 0; }
出力
string: "a b c d e" delims: " " result: "a" "b" "c" "d" "e" -------- string: "a,b,c,d,e" delims: "," result: "a" "b" "c" "d" "e" -------- string: "a b,c d,e" delims: " ," result: "a" "b" "c" "d" "e" -------- string: "a|b,c&d(e" delims: "|,&(" result: "a" "b" "c" "d" "e" -------- string: "abcde" delims: " " result: "abcde" --------