#navi(contents-page-name): No such page: 文字列

 指定した区切り文字で文字列を分割する・strtok

カンマなどの区切り文字がある文字列を指定した区切り文字で分割するstrtokについてのCサンプルコードと実行例を以下に記します。

c-top.html is not found or not readable.

関連記事

strtok書式

strtokの書式を以下に記します。

strtokのCサンプルコード

&ref(): File not found: "strtok.c" at page "文字列/指定した区切り文字で文字列を分割する・strtok"; (改行コードLF)

#include <stdio.h>
#include <string.h>
int main(void) {
    char s[] = "ubuntu,debian,fedora,redhat,suse,mint,vine";
    char *p = NULL;

    p = strtok(s, ",");
    while (p != NULL) {
        if (p != NULL) {
            printf("%s\n", p);
        }
        p = strtok(NULL, ",");
    }

    return 0;
}

1回目のstrtok関数では、文字列のポインタを渡していますが2回目以降はNULLになっているのがCサンプルコードから読むことができます。

strtokのCサンプルコードの実行結果

コンパイルし実行した結果を以下に記します。

$ gcc strtok.c -o strtok
$ ./strtok 
ubuntu
debian
fedora
redhat
suse
mint
vine

注意事項

上記サンプルコードの

char s[] = "ubuntu,debian,fedora,redhat,suse,mint,vine";

char *s = "ubuntu,debian,fedora,redhat,suse,mint,vine";

にするとSegmentation faultになります。

その理由は、char[]とchar*には違いがあります。

簡単に説明するとchar*で渡される文字列は変更禁止となります。
したがって、型があっているのでコンパイルは通りますが、実行時にSegmentation faultになるので注意が必要です。

以上、strtokのCサンプルコードでした。

c-btm.html is not found or not readable.

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS