分类: LINUX
2009-07-15 15:47:05
//注:有些函数名字后面有2的表示第二钟方法
size_t lm_strlen(const char *str){
int len;
for(len = 0; '\0' != *str++; )
++len;
return len;
}
size_t lm_strlen2(const char *str){
const char *psz = str;
while(*psz++)
;
return (psz-str-1);
}
/* 从src复制源字符串到dest,包括结束符'\0',如果dest数组容量不够,继续覆盖dest数组后面的内存
*/
char * lm_strcpy(char *dest, const char *src){
//if( (!dest)||(!src) ) return NULL; //通常为了保持高效不加判断
char *save = dest;
while(*dest++ = *src++)
;
return save;
}
char * lm_strncpy(char *dest, const char *src, size_t n){
char *start = dest;
char *end = dest + n;
while ((start < end) && (*start++ = *src++))
;
return (dest);
}
char * lm_strncpy2(char *dest, const char *src, size_t n){
if (n > 0) {
char *d = dest;
const char *s = src;
do {
if ((*d++ = *s++) == 0){
//如果n大于字符串src的长度,dest多余部分清0
while (--n != 0)
*d++ = 0;
break;
}
} while (--n != 0);
}
return dest;
}
char * lm_strcat (char *dest, const char *src){
//if( (!dest ) return NULL;
//if( !src ) return dest;
lm_strcpy (dest + lm_strlen (dest), src);
return dest;
}
char * lm_strcat2 (char *dest, const char *src){
char *save;
//if( (!dest ) return NULL;
//if( !src ) return dest;
for(save = dest; *dest; dest++ )
;
for( ; (*dest = *src); dest++, src++ )
;
return save;
}
char * lm_strncat (char *dest, const char *src, size_t n){
//if( (!dest ) return NULL;
//if( !src ) return dest;
lm_strncpy (dest + lm_strlen (dest), src, n);
return dest;
}
char * lm_strncat2 (char *dest, const char *src, size_t n){
char *save;
//if( (!dest ) return NULL;
//if( !src ) return dest;
for(save = dest; *dest; dest++ )
;
for( ; (n>0)&&(*dest = *src); dest++, src++, n--)
;
return save;
}
int lm_strcmp(const char *s1, const char *s2){
while (*s1 != '\0' && *s1 == *s2) {
s1++;
s2++;
}
return(*s1 - *s2);
}
int lm_strncmp(const char *s1, const char *s2, size_t n){
while (n-- > 0 && *s1 != '\0' && *s1 == *s2){
s1++;
s2++;
}
return(*s1 - *s2);
}
char * lm_strchr(const char *str, char c){
do{
if(*str == c)
return (char *)str;
}while(*str++);
return NULL;
}
char * lm_strstr(const char *s1, const char *s2){
const char *psz1 = s1;
const char *psz2 = s2;
if( (!s1)||(!s2) ) return NULL;
if( !(*s2) ) return NULL;
while(*s1){
psz1 = s1++;
psz2 = s2;
while(*psz1++ == *psz2++){
if(*psz2 == '\0')
return (char *)s1-1;
}
}
return NULL;
}
char * lm_strstr2(const char *s1, const char *s2){
size_t s2len = strlen(s2);
if( (!s1)||(!s2) ) return NULL;
if( s2len <= 0) return NULL;