回答編集履歴
1
追記
test
CHANGED
@@ -49,3 +49,67 @@
|
|
49
49
|
}
|
50
50
|
|
51
51
|
```
|
52
|
+
|
53
|
+
[追記] 少なからず小賢しい修正。第二引数:tokensにNULLを渡せば分割数が返ってくるので...:
|
54
|
+
|
55
|
+
```C
|
56
|
+
|
57
|
+
#include <stdio.h>
|
58
|
+
|
59
|
+
#include <stdlib.h>
|
60
|
+
|
61
|
+
#include <string.h>
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
int split(char* str, char* tokens[], const char* delim) {
|
66
|
+
|
67
|
+
char* last = str + strlen(str);
|
68
|
+
|
69
|
+
int count = 0;
|
70
|
+
|
71
|
+
for ( char* token = strtok(str, delim); token; token = strtok(NULL, delim)) {
|
72
|
+
|
73
|
+
if ( tokens ) { tokens[count] = token; }
|
74
|
+
|
75
|
+
else { token[strlen(token)] = *delim; *last = '\0'; }
|
76
|
+
|
77
|
+
++count;
|
78
|
+
|
79
|
+
}
|
80
|
+
|
81
|
+
return count;
|
82
|
+
|
83
|
+
}
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
int main() {
|
88
|
+
|
89
|
+
char input[] = "きょうは,とても,いい天気";
|
90
|
+
|
91
|
+
char** tokens;
|
92
|
+
|
93
|
+
int n = split(input, NULL, ","); // token数を求め
|
94
|
+
|
95
|
+
tokens = malloc(sizeof(char*)*n); // そんだけの領域を確保して
|
96
|
+
|
97
|
+
split(input, tokens, ","); // もっかい呼ぶ
|
98
|
+
|
99
|
+
int i;
|
100
|
+
|
101
|
+
for ( i = 0; i < n; ++i ) {
|
102
|
+
|
103
|
+
printf("[%s] ", tokens[i]);
|
104
|
+
|
105
|
+
}
|
106
|
+
|
107
|
+
printf("\n");
|
108
|
+
|
109
|
+
free(tokens);
|
110
|
+
|
111
|
+
return 0;
|
112
|
+
|
113
|
+
}
|
114
|
+
|
115
|
+
```
|