概要
- C言語で文字列を区切り文字ごとに分割したい
- よくあるサンプルだと元の文字列に変更を加えてしまう。今回はこれを防ぐために文字列のコピーを行う
参考
-
C言語で自作split関数 - Qiita
- このままだと元の文字列に変更を加えてしまう、文字列のコピーが必要
- C - mallocを使って新しい配列に文字列をコピーしたい|teratail
- C言語入門:文字列の長さを知る
実装
特定の文字で分割する関数
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
// MARK: - Helpers For Spliting String
int isDelimiter(char p, char delimiter) {
return p == delimiter;
}
char *copy_string(const char *a) {
int i;
char *c;
// a の長さをiに求める
for ( i = 0; a[i] != '\0'; ++i ) ;
// 文字列のコピーに必要な領域をcに確保する
c = (char*)malloc(sizeof(char) * (i+1)); // 終端文字を含んだ長さが必要
char *result = c;
// 文字列aをcにコピー
while (*a != '\0') {
*c = *a;
c++;
a++;
}
*c = '\0'; // '\0'で終端する
return result;
}
int split(char *dst[], char *_src, char delim) {
int count = 0;
char *src = copy_string(_src);
for(;;) {
while (isDelimiter(*src, delim)){
src++;
}
if (*src == '\0') {
break;
}
dst[count++] = src;
while (*src && !isDelimiter(*src, delim)) {
src++;
}
if (*src == '\0') {
break;
}
*src++ = '\0';
}
return count;
}
呼び出し例
// MARK: - Main
int main(int argc, const char * argv[]) {
char src[] = "ヒトカゲ,リザード,リザードン";
char *dst[100]; // 分割結果を格納
int count = split(dst, src, ',');
char pokemon_1[64];
char pokemon_2[64];
char pokemon_3[64];
for(int i = 0; i < count; i++){
unsigned long size = sizeof(char) * strlen(dst[i]);
switch (i) {
case 0:
strncpy(pokemon_1, dst[i], size);
break;
case 1:
strncpy(pokemon_2, dst[i], size);
break;
case 2:
strncpy(pokemon_3, dst[i], size);
break;
default:
break;
}
}
printf("元の文字列: %s\n", src);
printf("pokenon_1: %s\n", pokemon_1);
printf("pokenon_2: %s\n", pokemon_2);
printf("pokenon_3: %s\n", pokemon_3);
return 0;
}
出力結果
元の文字列: ヒトカゲ,リザード,リザードン
pokenon_1: ヒトカゲ
pokenon_2: リザード
pokenon_3: リザードン