0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C言語で文字列を区切り文字ごとに分割する

Posted at

概要

  • 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: リザードン
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?