標準/拡張機能 | C/C++ | 依存項目 |
---|---|---|
ISO C |
両方 |
#include <string.h>
char *strtok(char * __restrict__string1, const char * __restrict__string2);
string1 で示される文字ストリングをトークンの シーケンスに分けます。トークンは、string2 で示されるストリングの文字に よって、互いに分離されます。
トークンは、string2 で示されるストリングにない 先頭文字で開始します。このような文字が検出されないと、トークンはストリングにあり ません。strtok() は、NULL ポインターを戻します。トークンは、string2 で示されるストリングに含まれる 先頭文字で終了します。このような文字が検出されないと、トークンは終了 NULL 文字で終了 します。strtok() への以後の呼び出しは、NULL ポインターを戻します。この ような文字が検出される 場合には、これはトークンを 終了させる 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
*
* 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"