strpbrk函数

/*
strpbrk函数
用法:#include <string.h>
功能:依次检验字符串s1中的字符,当被检验字符在字符串s2中也包含时,则停止检验,并返回该字符位置,空字符NULL不包括在内。
说明:返回s1中第一个满足条件的字符的指针,如果没有匹配字符则返回空指针NULL。
用途:在源字符串(s1)中找出最先含有搜索字符串(s2)中任一字符的位置并返回,若找不到则返回空指针。

这个函数与strscpn只有两个差异,返回值是指针类型
没有匹配字符则返回空指针NULL,即不匹配NULL字符。
*/

 


 

#include <stdio.h>

char* strpbrk(const char *s1, const char *s2)
{//可以看到这个程序和strcspn很类似。
	const char *p;
	const char *r;

	for (p = s1; *p != '\0'; p++)
	{
		for (r = s2;*r != '\0'; r++)
		{
			if (*p == *r)
			{
				return (char*) p;   //如果找到,则返回p指针,指向第一个匹配字符。
			}
		}
	}

	return NULL;//没有找到,返回NULL
}

int main() 
{
    char* input = "hello world friend of mine";
    char* space = " ";
    char* pos = input;
    int word_counter = 0;
 
    do {
        pos = strpbrk(pos, space);
        word_counter++;
        pos ? pos++ : pos;
        printf("%d\n", word_counter);
    } while (pos != NULL);
}


linux源码

#ifndef __HAVE_ARCH_STRPBRK   
/** 
 * strpbrk - Find the first occurrence of a set of characters 
 * @cs: The string to be searched 
 * @ct: The characters to search for 
 */  
char *strpbrk(const char *cs, const char *ct)  
{  
    const char *sc1, *sc2;  
  
    for (sc1 = cs; *sc1 != '\0'; ++sc1) {  
        for (sc2 = ct; *sc2 != '\0'; ++sc2) {  
            if (*sc1 == *sc2)  
                return (char *)sc1;  
        }  
    }  
    return NULL;  
}  
EXPORT_SYMBOL(strpbrk);  
#endif   


 

** strpbrk.c - locate multiple characters in a string */

/** Copyright (C) 1991, 1994 Free Software Foundation, Inc.

   NOTE: The canonical source of this file is maintained with the GNU C Library.
   Bugs can be reported to bug-glibc@prep.ai.mit.edu.

   This file is part of GNU Bash, the Bourne Again SHell.

   Bash is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Bash is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Bash.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#if !defined (HAVE_STRPBRK)

#include <stdc.h>

/** Find the first ocurrence in S of any character in ACCEPT.  */
char *
strpbrk (s, accept)
     register const char *s;
     register const char *accept;
{
  while (*s != '\0')
    {
      const char *a = accept;
      while (*a != '\0')
	if (*a++ == *s)
	  return (char *) s;
      ++s;
    }

  return 0;
}
#endif


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值