ในส่วนนี้ เราจะมาดูวิธีการ tokenize สตริงใน C. C มีฟังก์ชันไลบรารีสำหรับสิ่งนี้ ฟังก์ชันไลบรารี C char *strtok(char *str, const char *delim) แบ่งสตริง str เป็นชุดของโทเค็นโดยใช้ตัวคั่น ตัวคั่น
ต่อไปนี้เป็นการประกาศสำหรับฟังก์ชัน strtok()
char *strtok(char *str, const char *delim)
ต้องใช้สองพารามิเตอร์ str - เนื้อหาของสตริงนี้ได้รับการแก้ไขและแบ่งออกเป็นสตริงที่เล็กกว่า (โทเค็น) และตัวคั่น - นี่คือสตริง C ที่มีตัวคั่น สิ่งเหล่านี้อาจแตกต่างกันไปในการโทรแต่ละครั้ง ฟังก์ชันนี้ส่งคืนตัวชี้ไปยังโทเค็นแรกที่พบในสตริง ตัวชี้ค่า null จะถูกส่งคืนหากไม่มีโทเค็นเหลือให้ดึงข้อมูล
โค้ดตัวอย่าง
#include <string.h>
#include <stdio.h>
int main () {
char str[80] = "This is - www.tutorialspoint.com - website";
const char s[2] = "-";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
} ผลลัพธ์
This is www.tutorialspoint.com website