strtok_r 和 strsep 使用实例

这两个函数都是拆分字符的API,都是线性安全函数,特意写了个实例对比两个函数的不通,从MAN手册中可以看出两个函数都会改变原有字符串。

strsep() function was introduced as a replacement for strtok(3), since the latter cannot handle empty fields. However, strtok(3) conforms to C89/C99 and hence is more portable.

也就是说strsep是strtok的替代接口,但可能在移植的时候会出现问题。

#include 
#include  
#include  

int main() 
{ 
	char ptr[]={ "abc;defghijk;     lmnopqrst ;uvwxyz "}; 
	char *p = ptr, *str= "; "; 
	int i = 0;
	char *sep = NULL;

	printf("Original string : %s\n", ptr);
	while((sep = strsep(&p, str)) != NULL)
	{
		if(!strcmp(sep, ""))
		{
			printf("more than %s appear \n", sep);
			continue;
		}
		printf("Line %d: %s\n", ++i, sep);	
	}
	
	return 0;
} 
输出结果:

TestServer $ ./strsep 
Original string : abc;defghijk;     lmnopqrst ;uvwxyz 
Line 1: abc
Line 2: defghijk
more than  appear 
more than  appear 
more than  appear 
more than  appear 
more than  appear 
Line 3: lmnopqrst
more than  appear 
Line 4: uvwxyz
more than  appear 

会多次出现空字符串的问题,这是因为strsep在处理多余一个的delimit字符是会返回空字符串代替NULL。

#include 
#include  
#include  

int main() 
{ 
	char ptr[]={ "abc;defghijk;     lmnopqrst ;uvwxyz "}; 
	char *p = ptr, *dlm= "; "; 
	int i = 0;
	char *sep = NULL, *saveptr = NULL;

	printf("Original string : %s\n", ptr);
	while((sep = strtok_r(p, dlm, &saveptr)) != NULL)
	{
		printf("Line %d: %s\n", ++i, sep);	
		// note: p have to set NULL, or will not break while();
		p = NULL;
	}
	
	return 0;
} 

输出结果:TestServer$ ./strtok_r Original string : abc;defghijk; lmnopqrst ;uvwxyz 

Line 1: abc

Line 2: defghijk

Line 3: lmnopqrst

Line 4: uvwxyzstrtok 

函数会将多余一个delimit字符转换成'\0', 注意p = NULL操作,在第二次调用strtok&strtok_r时需要将str=NULL。

你可能感兴趣的:(Unix/Linux)