C语言字符串处理函数 C语言字符串处理函数

http://blog.csdn.net/ruizeng88/article/details/6677736
 
 

1.字符串比较

int strcmp(const char *s1, const char *s2);

比较两个字符串的大小(不忽略大小写),返回值很有学问:如果s1小于s2返回一个小于0的数,如果s1大于s2返回一个大于0的数,如果相等则返回0。返回值是两个字符串中第一个不相等的字符ascii码的差值。实现如下:

 

  1. int my_strcmp(const char *s1, const char *s2){  
  2.     //important! validate arguments first!   
  3.     assert(NULL !=s1 && NULL != s2);  
  4.     while(*s1 != ' ' && *s2 != ' ' && *s1==*s2){  
  5.         s1++;  
  6.         s2++;  
  7.     }  
  8.     return *s1 - *s2;  
  9. }  
int my_strcmp(const char *s1, const char *s2){
	//important! validate arguments first!
	assert(NULL !=s1 && NULL != s2);
	while(*s1 != ' ' && *s2 != ' ' && *s1==*s2){
		s1++;
		s2++;
	}
	return *s1 - *s2;
}

注意再函数开始进行参数检查,防止输入参数有NULL时发生运行时错误。

strcmp是最常用的字符串比较函数,一般用法是if(!strcmp(s1, s2)){ ...}。如果不是对整个字符串进行比较而只是比较指定数目的字符串,可以使用函数:

int strncmp(const char *s1, const char *s2, size_t n);

用法和返回值都和strcmp类似,之比较给定字符串的前n个字符,或者到遇到任一字符串结尾。实现如下:

 

  1. int my_strncmp(const char *s1, const char *s2, size_t n){  
  2.     //important! validate arguments first!   
  3.     assert(NULL!=s1 && NULL!=s2);  
  4.     if(n == 0)  
  5.         return 0;  
  6.     size_t cnt = 1;  
  7.     while(*s1 != ' ' && *s2 != ' ' && *s1==*s2 && cnt < n){  
  8.         s1++;  
  9.         s2++;  
  10.         cnt++;  
  11.     }  
  12.     return *s1 - *s2;  
  13. }  
int my_strncmp(const char *s1, const char *s2, size_t n){
	//important! validate arguments first!
	assert(NULL!=s1 && NULL!=s2);
	if(n == 0)
		return 0;
	size_t cnt = 1;
	while(*s1 != ' ' && *s2 != ' ' && *s1==*s2 && cnt < n){
		s1++;
		s2++;
		cnt++;
	}
	return *s1 - *s2;
}
需要注意的除了参数检查外,还要注意n=0的特殊情况,这里我们n=0永远返回0。

还有其他一些带特殊要求字符串比较函数,如:

stricmp,memcmp,memicmp等等,加i表示比较时忽视大小写,带mem的是比较一块内存区间。

2.字符串查找

最简单的是查找字符串查找字符:

char *strchr(const char *s, int c);

至于参数为什么是int,历史遗留问题,这里不多讨论。函数返回在s中找到的第一个c的位置的指针,注意的是,字符串末尾的‘