C言語のsplit関数の使い方は?
C言語にはsplit関数は備わっていません。その代わりに、自分でそのような関数を定義して、類似の機能を組み入れることが可能です。以下は、文字列を指定されたセパレータを使って分割するサンプル関数です。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** split(const char* str, const char* delimiter, int* count) {
char* copy = strdup(str); // 复制原始字符串
char* token = strtok(copy, delimiter); // 分割第一个子串
char** result = NULL;
int i = 0;
while (token != NULL) {
result = realloc(result, sizeof(char*) * (i + 1)); // 分配空间存储子串的指针
result[i] = strdup(token); // 复制子串
i++;
token = strtok(NULL, delimiter); // 继续分割下一个子串
}
free(copy); // 释放复制的字符串
*count = i; // 子串的数量
return result;
}
int main() {
const char* str = "Hello,World,!";
const char* delimiter = ",";
int count;
char** tokens = split(str, delimiter, &count);
for (int i = 0; i < count; i++) {
printf("%s\n", tokens[i]);
}
// 释放内存
for (int i = 0; i < count; i++) {
free(tokens[i]);
}
free(tokens);
return 0;
}
例に示すように、split 関数は指定された区切り文字(例:カンマ)に従って文字列を複数の部分文字列に分割し、文字列ポインタの配列を返します。各部分文字列は独立した文字列で、動的に割り当てられたメモリに格納されます。この関数はまた、分割後の部分文字列の数を返す整数のポインタを受け付けます。サンプルプログラムでは、”Hello,World,!” をカンマで分割し、分割された部分文字列を出力します。
split 関数を使用した後は、メモリリークを防ぐために、返却された文字列ポインタの配列と各サブストリングのメモリを解放する必要があることに注意してください。