讀取檔案時,時常需要處理字串,才能進行後續的動作。而我最常使用的函式是strtok,看了網路上的範例後直接拿來使用,然而卻不太曉得strtok的運作原理。這裡有圖解,讓我發出「啊哈」的驚嘆!
首先來看一下程式碼:
/**
Theme: strtok
Compiler: Dev C++ 4.9.9.2
Date: 100/07/10
Author: ShengWen
Blog: https://cg2010studio.wordpress.com/
*/
#include <iostream>
char string[] = "a string,of ,,tokens";
char *token;
int main(){
token = strtok(string," ,"); /*There are two delimiters here*/
while (token != NULL){
printf("The token is: %s\n", token);
token = strtok(NULL," ,");
}
system("pause");
return EXIT_SUCCESS;
}
輸出結果:
The token is: a
The token is: string
The token is: of
The token is: tokens
請按任意鍵繼續 . . .
接下來就是圖解時間:
char * strtok ( char * str, const char * delimiters );

在區隔字元中插入結束字元(),使得在列印token時遇到結束字元能停下來。果然還是加上圖解比較好理解,不然之前我都只死背那幾行程式碼。
Comments on: "[C&C++] strtok" (1)
寫 Flutter 需要用到 C/C++,來複習一下~
int testECHO(int argc, char *argv)
讚讚