😸
[C] strtok 関数
機能
文字列を区切り文字で分割する関数[1]
使用例
apple
と banana
を順に表示する
\n
は改行を表す エスケープシーケンス[2]
コード
char str[] = "apple,banana";
char *token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
全文
#include <stdio.h>
#include <string.h>
void main() {
char str[] = "apple,banana";
char *token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
}
実行結果
apple
banana
cat
, dog
, fish
をスペース区切りの文字列から順に表示する
コード
char str[] = "cat dog fish";
char *token = strtok(str, " ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
全文
#include <stdio.h>
#include <string.h>
void main() {
char str[] = "cat dog fish";
char *token = strtok(str, " ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
}
実行結果
cat
dog
fish
Discussion