新浪博客

c语言中关于字符串查找与匹配的函数

2006-12-28 10:33阅读:
定义函数:int memcmp(const void *s1, const void *s2, size_t n)
函数说明:memcmp()用来比较s1和s2所指的内存区间前n个字符。字符串大小的比较是以ASCII码表上的顺序来决定,此顺序亦为字符的值。 memcmp()首先将s1第一个字符值减去s2第一个字符值,若差值为0则再继续比较下个字符,若差值不为0则将差值返回。如字符串'Ac'和'ba' 比较则会返回字符‘A’(65)和'b'(98)的差值-33
返回值 :若参数s1和s2所指定的内存内容都完全相同则返回0值。 s1若大于s2则返回大于0的值。s1若小于s2则返回小于0的值
范例:
#include <string.h>
main()
{
char *a='aBcDeF';
char *b='AbCdEf';
printf('%d', memcmp((void *) a, (void *) b, 6));
}
定义函数:直接在start指针指向的存储单元里查找find指针指向的字符串,
如果找到,返回指向子串的指针,否则返回空指针.
void *memmem(void *start, unsigned int s_len, void *find,
unsigned int f_len)

{
char *p, *q;
unsigned int len;
p = start, q = find;
len = 0;
while((p - (char *)start + f_len) <= s_len){
while(*p++ == *q++){
len++;
if(len == f_len)
return(p - f_len);
};
q = find;
len = 0;
};
return(NULL);
}
函数strstr()
- locate a substring
SYNOPSIS
#include <string.h>
char *strstr(const char *haystack, const char *needle);
DESCRIPTION
The strstr() function finds the first occurrence of the substring nee-
dle in the string haystack. The terminating `\0' characters are not
compared.
RETURN VALUE
The strstr() function returns a pointer to the beginning of the sub-
string, or NULL if the substring is not found.
BUGS
Early versions of Linux libc (like 4.5.26) would not allow an empty
argument. Later versions (like 4.6.27) work correctly, and return
haystack when needle is empty.

我的更多文章

下载客户端阅读体验更佳

APP专享