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 <stdio.h>
#include <string.h> 
#include <stdlib.h> 

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 <stdio.h>
#include <string.h> 
#include <stdlib.h> 

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值