c語言的字符串分解——strtok函數和strsep函數

今天才知道原來C語言也有類似java的split的函數,按特定字符對字符串進行分解:

strtok的解釋和示例:

strtok
Syntax:
#include <cstring> char *strtok( char *str1, const char *str2 );

The strtok() function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token. strtok() returns NULL if no token is found. In order to convert a string to tokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after this should have str1 be NULL.

For example:

	char str[] = "now # is the time for all # good men to come to the # aid of their country";
	char delims[] = "#";
	char *result = NULL;
	result = strtok( str, delims );
	while( result != NULL ){
		printf( "result is \"%s\"\n", result );
		result = strtok( NULL, delims );
	}

The above code will display the following output:

result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country" 

在str1中找出以str2中出現的字符爲分隔的字符串(注:並不是以該字符串爲分隔),即是源串中除去了含有分隔串中的所有字符後餘下的一段段的字符串,每調用一次找到一串,找不到則返回空串。第一次調用必須傳給它有效的字符串,第二次傳NULL就可以了,每次調用返回找到的子串的時候都會把源串中該子串的尾部字符(原來是搜索串中的某一字符)修改成'/0'字符返回值爲每次調用得到的字串。
但是百度百科裏面又有提到說“最新的Linux內核2.6.29,說明了這個函數已經不再使用,由速度更快的strsep()代替”。所以又去查了下strsep函數:
原型:char *strsep(char **stringp, const char *delim);
功能:分解字符串爲一組字符串。從stringp指向的位置起向後掃描,遇到delim指向位置的字符後,將此字符替換爲NULL,返回stringp指向的地址。

但是strsep函數,在 Windows是沒有支持的,我是在Linux環境,所以ok~

給個例子:

char str2[] = "2011/11/28";
	char *buf;
	char *token;
	buf = str2;
	while((token = strsep(&buf, "/")) != NULL){
		printf("%s\n", token);
	}

輸出:

2011
11
28









發佈了41 篇原創文章 · 獲贊 2 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章