2
2

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 5 years have passed since last update.

strtokの部分文字列分割対応版

Last updated at Posted at 2014-08-05
  • 文字コードは UTF-8 である前提です。Shift_JISやEUC-JPなどは正しく処理することは出来ません。
  • 以下のバージョンでは、デリミタを複数指定することは出来ません。
strstok関数
# include <stdio.h>
# include <string.h>

char *strstok(char *str, const char *delimiter) {
    static char *ptr = NULL;
    char *boundary;
    if (!str) {
        str = ptr;
    }
    if (!str) {
        return NULL;
    }
    if (boundary = strstr(str, delimiter)) {
        *boundary = '\0';
        ptr = boundary + strlen(delimiter);
        return str;
    }
    ptr = NULL;
    return str;
}

int main(void) {
    char str[] = "あいうえをかきくけをさしすせ";
    char delim[] = "を";
    char *p;
    for (p = strstok(str, delim); p; p = strstok(NULL, delim)) {
        puts(p);
    }
    return 0;
}
  • 以下のバージョンでは、デリミタを複数指定することが可能です。
strstoks関数
# include <stdio.h>
# include <string.h>
 
char *strstoks(char *str, const char **delimiters, const int delimiters_size) {
    static char *ptr = NULL;
    char *boundary;
    int i;
    if (!str) {
        str = ptr;
    }
    if (!str) {
        return NULL;
    }
    for (i = 0; i < delimiters_size; ++i) {
        if (boundary = strstr(str, delimiters[i])) {
            *boundary = '\0';
            ptr = boundary + strlen(delimiters[i]);
            return str;
        }
    }
    ptr = NULL;
    return str;
}
 
int main(void) {
    int size = 2;
    char str[] = "あいうえおかきくけこさしすせ";
    char *delims[] = {"お", "こ"};
    char *p;
    for (p = strstoks(str, delims, size); p; p = strstoks(NULL, delims, size)) {
        puts(p);
    }
    return 0;
}
2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?