Linux中strchr与strstr函数实现。

<span style="font-size:18px;"><strong></strong></span>
</pre><pre code_snippet_id="354054" snippet_file_name="blog_20140520_2_3457534" name="code" class="cpp"><p>#ifndef __HAVE_ARCH_STRCHR</p>/**strchr - Find the first occurrence of a character in a string
 * @s: The string to be searched
 * @c: The character to search for
 */
char *strchr(const char *s, int c)//定义函数接口的方式学一下,
{
	for (; *s != (char)c; ++s)
		if (*s == '\0')
			return NULL;
	return (char *)s;
}
EXPORT_SYMBOL(strchr);

————————————————————————————————————————————————

上面中把强制类型中放在for中,则每次都要强制一次,可以把char ctemp=(char)c;

for(;ctemp!=*s;++s)
	if(*s=='\0')
		return NULL;
return (char*) s;


上面中把强制类型中放在for中,则每次都要强制一次,可以把char ctemp=(char)c;

for(;ctemp!=*s;++s)
	if(*s=='\0')
		return NULL;
return (char*) s;

________________________________________________________

同时还要注意一下for中的++s,虽然效果与s++一样,但效率可能不一样,

在编译器没有优化的情况下s++,表达式是i加1之前的副本,因为要存储这个副本,
所以会多一些开销。单独在for中的s++;是个表达式,这个表达式与i相关的,
即表达式的值为i,但 这个表达式之后,i为i+1;
而++i;这个表达式的i是直接加1,也为i本身。表达式的值与i的值相同。
http://blog.csdn.net/zy1691/article/details/4849808

——————————————————————————————————————


static inline char *strchr(const char *s, int c)
{
char sc, ch = c;
for (; (sc = *s++) != ch; ) {
if (!sc)
return NULL;
}
return (char *)s - 1;
}


——————————————————————————————————————————————

**
* strstr - Find the first substring in a %NUL terminated string
* @s1: The string to be searched
* @s2: The string to search for
*/
char *strstr(const char *s1, const char *s2)
{
	int l1, l2;
	l2 = strlen(s2);
	if (!l2)
		return (char *)s1;
	l1 = strlen(s1);
	while (l1 >= l2) {
		l1--;
		if (!memcmp(s1, s2, l2))
			return (char *)s1;
		s1++;
	}
	return NULL;
}
————————————————————————————————————————————————
另一种方式
#ifndef HAVE_STRSTR
char *strstr(char *s1, char *s2)
{ /* from libiberty */
char *p;
int len = strlen(s2); if (*s2 == '\0') /* everything matches empty string */
return s1;
for (p = s1; (p = strchr(p, *s2)) != NULL; p = strchr(p + 1, *s2)) {
if (strncmp(p, s2, len) == 0)
return (p);
}
return NULL;
}
#endif


<pre code_snippet_id="354054" snippet_file_name="blog_20140520_7_5009612">
<pre code_snippet_id="354054" snippet_file_name="blog_20140520_18_5249713" name="code" class="cpp"><pre code_snippet_id="354054" snippet_file_name="blog_20140520_18_5249713">
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值