LoginSignup
0
0

More than 1 year has passed since last update.

Cでsplit関数

Posted at

メモです
使いたいときに毎度考えて書くのが面倒なので

つくりは割と粗めかもです

コード

split.c

#include <string.h>

int split(char* str, char regex, char** buf, size_t buflen){
    int strlength = strlen(str);
    int length = 1;
    buf[0] = str;
    for(int i = 1; i < strlength; i++){
        if(str[i] == regex){
            str[i] = '\0';
            buf[length] = &str[i + 1];
            length++;
            if(buflen <= length)break;
        }
    }
    return length;
}

 /*テスト用
#include <stdio.h>
int main(int argc, char const *argv[])
{
    
    //私の趣味だ、いいだろう
    char str[] ="フラファル リキタル ウンスキン キタスイ";
    char* buf[100];
    printf("%s\n", str);
    int test = split(str, ' ', buf, 100);
    for(int i = 0; i < test; i++){
        printf("%s\n",buf[i]);
    }
    return 0;
}
 */

引数strが引用する文字列
引数regexが分割するための文字の引数
引数bufはその分割した配列を入れるためのバッファ
引数buflenは そのバッファのサイズ

戻り値は、その配列の個数が返ってきます

strの中身をそのまま書き換えている関係上
この関数に入れたstrは正常な動きをしなくなるので
そこのところだけ注意

実行してみる

とりあえずテスト用のメインを実行してみます

実行結果
$gcc split.c
$./a.out
フラファル リキタル ウンスキン キタスイ
フラファル
リキタル
ウンスキン
キタスイ

うん、いい感じ

0
0
2

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
0