回答編集履歴
2
コードの間違いの修正
test
CHANGED
@@ -1,6 +1,6 @@
|
|
1
|
-
|
1
|
+
assign()ではなくsubstr()を使う方法でコーディングしてみました。
|
2
2
|
|
3
|
-
|
3
|
+
参考サイト:[C++ 区切り文字/文字列による文字列の分割(split)std::string/文字列ポインタ](http://marycore.jp/prog/cpp/std-string-split/)
|
4
4
|
|
5
5
|
```C++
|
6
6
|
|
@@ -16,15 +16,31 @@
|
|
16
16
|
|
17
17
|
{
|
18
18
|
|
19
|
-
_
|
19
|
+
int delim_length = delimiter.length();
|
20
20
|
|
21
|
-
|
21
|
+
string::size_type pos = 0;
|
22
22
|
|
23
|
+
string::size_type offset = 0;
|
24
|
+
|
25
|
+
for(int i = 0; i < number + 1; i++) {
|
26
|
+
|
23
|
-
|
27
|
+
pos = input_str.find(delimiter, offset);
|
28
|
+
|
29
|
+
if (pos == string::npos) {
|
30
|
+
|
31
|
+
return input_str.substr(offset);
|
32
|
+
|
33
|
+
}
|
34
|
+
|
35
|
+
if (i < number) {
|
36
|
+
|
37
|
+
offset = pos + delim_length;
|
38
|
+
|
39
|
+
}
|
24
40
|
|
25
41
|
}
|
26
42
|
|
27
|
-
return input_str.
|
43
|
+
return input_str.substr(offset, pos - offset);
|
28
44
|
|
29
45
|
}
|
30
46
|
|
@@ -36,9 +52,61 @@
|
|
36
52
|
|
37
53
|
string ss = "aaaaa bbb cccc dddddd ff gggg hhhhhhh";
|
38
54
|
|
39
|
-
string ss_2 = GetSplittedStrAt(ss, " ", 2);
|
55
|
+
string ss_2 = GetSplittedStrAt(ss, " ", 2); // Output: cccc
|
40
56
|
|
57
|
+
cout << ss_2 << std::endl;
|
58
|
+
|
59
|
+
|
60
|
+
|
61
|
+
// 参考
|
62
|
+
|
63
|
+
string ss_0 = GetSplittedStrAt(ss, " ", 0);
|
64
|
+
|
65
|
+
string ss_1 = GetSplittedStrAt(ss, " ", 1);
|
66
|
+
|
67
|
+
// ss_2は定義済み
|
68
|
+
|
69
|
+
string ss_3 = GetSplittedStrAt(ss, " ", 3);
|
70
|
+
|
71
|
+
string ss_4 = GetSplittedStrAt(ss, " ", 4);
|
72
|
+
|
73
|
+
string ss_5 = GetSplittedStrAt(ss, " ", 5);
|
74
|
+
|
75
|
+
string ss_6 = GetSplittedStrAt(ss, " ", 6);
|
76
|
+
|
77
|
+
cout << ss_0 << endl;
|
78
|
+
|
79
|
+
cout << ss_1 << endl;
|
80
|
+
|
41
|
-
cout << ss_2 << endl;
|
81
|
+
cout << ss_2 << endl;
|
82
|
+
|
83
|
+
cout << ss_3 << endl;
|
84
|
+
|
85
|
+
cout << ss_4 << endl;
|
86
|
+
|
87
|
+
cout << ss_5 << endl;
|
88
|
+
|
89
|
+
cout << ss_6 << endl;
|
90
|
+
|
91
|
+
/*
|
92
|
+
|
93
|
+
Output:
|
94
|
+
|
95
|
+
aaaaa
|
96
|
+
|
97
|
+
bbb
|
98
|
+
|
99
|
+
cccc
|
100
|
+
|
101
|
+
dddddd
|
102
|
+
|
103
|
+
ff
|
104
|
+
|
105
|
+
gggg
|
106
|
+
|
107
|
+
hhhhhhh
|
108
|
+
|
109
|
+
*/
|
42
110
|
|
43
111
|
return 0;
|
44
112
|
|
1
コードのわかりやすさの向上
test
CHANGED
@@ -12,7 +12,7 @@
|
|
12
12
|
|
13
13
|
|
14
14
|
|
15
|
-
string GetSplittedStr(string input_str, string delimiter, int number)
|
15
|
+
string GetSplittedStrAt(string input_str, string delimiter, int number)
|
16
16
|
|
17
17
|
{
|
18
18
|
|
@@ -36,7 +36,7 @@
|
|
36
36
|
|
37
37
|
string ss = "aaaaa bbb cccc dddddd ff gggg hhhhhhh";
|
38
38
|
|
39
|
-
string ss_2 = GetSplittedStr(ss, " ", 2);
|
39
|
+
string ss_2 = GetSplittedStrAt(ss, " ", 2);
|
40
40
|
|
41
41
|
cout << ss_2 << endl; // Output: cccc
|
42
42
|
|