こんなん書いてみた。
C++
1#include <string>
2
3template<typename String,typename OutputIterator>
4OutputIterator tokenize(const String& str, const String& delim, OutputIterator out) {
5 for ( typename String::size_type spos, epos = 0;
6 (spos = str.find_first_not_of(delim, epos)) != String::npos;) {
7 *out++ = str.substr(spos,(epos = str.find_first_of(delim, spos))-spos);
8 }
9 return out;
10}
11
12/* おためし */
13#include <iostream>
14#include <vector>
15
16int main() {
17 using namespace std;
18
19 vector<string> input = {
20 "abc",
21 "a bb ccc",
22 " a bb ccc",
23 "a bb ccc ",
24 " a bb ccc dddd ",
25 " ",
26 ""
27 };
28 for ( const auto& item : input ) {
29 using namespace std::literals::string_literals;
30 cout << '[' << item << "] -> ";
31 vector<string> out;
32 tokenize(item, " "s, back_inserter(out));
33 for ( const auto& token : out ) {
34 cout << '[' << token << "] ";
35 }
36 cout << endl;
37 }
38
39}
40/* 実行結果
41[abc] -> [abc]
42[a bb ccc] -> [a] [bb] [ccc]
43[ a bb ccc] -> [a] [bb] [ccc]
44[a bb ccc ] -> [a] [bb] [ccc]
45[ a bb ccc dddd ] -> [a] [bb] [ccc] [dddd]
46[ ] ->
47[] ->
48*/
[追記] こっち↓の方がツブシが利くかなー...
C++
1template<typename String,typename Function>
2void tokenize(const String& str, const String& delim, Function&& fun) {
3 for ( typename String::size_type spos, epos = 0;
4 (spos = str.find_first_not_of(delim, epos)) != String::npos;) {
5 fun(str.substr(spos,(epos = str.find_first_of(delim, spos))-spos));
6 }
7}
8
9/* おためし */
10#include <iostream>
11#include <string>
12
13int main() {
14 using namespace std;
15 string input[] = {
16 "abc",
17 "a bb ccc",
18 " a bb ccc",
19 "a bb ccc ",
20 " a bb ccc dddd ",
21 " ",
22 ""
23 };
24 for ( const auto& item : input ) {
25 using namespace std::literals::string_literals;
26 cout << '[' << item << "] -> \n ";
27 int count = 0;
28 auto print = [&](const string& token) { cout << ++count << '[' << token << "] ";};
29 tokenize(item, " "s, print);
30 cout << endl;
31 }
32
33}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/02/12 02:10