strtok() - ストリングのトークン化

標準

標準/拡張機能 C/C++ 依存項目

ISO C
XPG4
XPG4.2
C99
Single UNIX Specification、バージョン 3

両方  

形式

#include <string.h>

char *strtok(char * __restrict__string1, const char * __restrict__string2);

機能説明

string1 で示される文字ストリングをトークンの シーケンスに分けます。トークンは、string2 で示されるストリングの文字に よって、互いに分離されます。

トークンは、string2 で示されるストリングにない 先頭文字で開始します。このような文字が検出されないと、トークンはストリングにあり ません。strtok() は、NULL ポインターを戻します。トークンは、string2 で示されるストリングに含まれる 先頭文字で終了します。このような文字が検出されないと、トークンは終了 NULL 文字で終了 します。strtok() への以後の呼び出しは、NULL ポインターを戻します。この ような文字が検出される 場合には、これはトークンを 終了させる NULL 文字で上書きされます。

strtok() への次回の呼び出しで string1 に NULL ポインター が指定された場合には、前回の呼び出しで検出および上書きされた 文字の後の最初の文字で、トークン化が再開されます。例えば、次のようになります。
/* Here are two calls  */
strtok(string," ")
strtok(NULL," ")


/* Here is the string they are processing */
                   abc defg hij
    first call finds  ↑
                       ↑ second call starts

戻り値

strtok() の最初の呼び出し時に、string1 の最初のトークンへの ポインターを戻します。同じトークン・ストリングでの以後の呼び出しで、strtok() は、ストリング内の次のトークンへのポインターを戻します。トークンがそれ以上ないときには、NULL ポインターを戻します。トークンのすべては NULL 終了されます。

CELEBS54
⁄* CELEBS54
 *
 * strtok() example:
 * 
 * This example parses tokens separated by commas, blanks and semicolons,
 * from a string until no tokens are left.  As the string is parsed,
 * pointers to the the following tokens are returned by strtok(),
 * and these tokens are written to stdout:
 *
 *   a
 *   string
 *   of
 *   tokens
 *
 * The final call to strtok() returns NULL indicating that 
 * there are no more tokens.
 *
 * Note that as the string is tokenized, it will be overwritten.
 *
 *⁄

#include <stdio.h>
#include <string.h>

int main(void)
{
   char *token, string[] = "a string, of,; ;;;,tokens¥0,after null terminator";

   token = strtok(string, ", ;");
   do
   {
      printf("token: ¥"%s¥"¥n", token);
   }
   while (token = strtok(NULL, ", ;"));

}
出力:
token: "a string"
token: " of"
token: " "
token: "tokens"

関連情報