天天看點

c函數: strtok和strtok_r

strtok用來截字元串中的前後字元串.

strtok可以根據使用者所提供的分割符,将一段字元串分割直到遇到"\0".

#include <stdio.h>
#include <string.h>

int main(void)
{
	char input[16] = "abc,d";
	char *p;

	p = strtok(input, ",");
	if(p)
		printf("%s\n", p);

	p = strtok(NULL, ",");
	if(p)
		printf("%s\n", p);
	return 0;
}
           

輸出結果:

abc

d

真是想不明白,第二次調用strtok時,第一個參數竟然為NULL,接着輸出","後面的結果.這麼寫的話,明顯讓人感覺有bug似的.這個庫也不知道是誰封的?

強行記住吧.

看看三個參數的分割:

#include <stdio.h>
#include <string.h>

int main(void)
{
	int i = 0;
	char buffer[] = "Fred,John,Ann";
	char *p[3];
	char *buff = buffer;

	while((p[i] = strtok(buff, ",")) != NULL){
		printf("%s\n", p[i]);
		i++;
		buff = NULL;	
	}
	return 0;
}
           

結果 :

Fred

John

Ann

strtok_r中的r意思是reentrant.可重入的意思.

作者:張亮校

日期:2013.01.09

繼續閱讀