Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

String tokenisation function ใน C


ในส่วนนี้เราจะดูวิธี tokenize strings ใน C C มี library function สำหรับนี้ ฟังก์ชัน char *strtok(char *str, const char *delim) breaks string str เป็น series of tokens โดยใช้ delimiter delim.

Declaration สำหรับ strtok():

char *strtok(char *str, const char *delim)

รับ 2 parameters str - เนื้อหาของ string นี้จะถูก modify และแยกเป็น smaller strings (tokens) delim - C string ที่มี delimiters อาจแตกต่างไปในแต่ละ call คืน pointer ไปยัง token แรก พบใน string คืน null pointer หากไม่มี tokens เหลือ

ตัวอย่างโค้ด

#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