strstr函数

来源:互联网 发布:什么是淘宝口令 编辑:程序博客网 时间:2024/04/29 22:58

/*
包含文件:string.h
函数名: strstr
函数原型:extern char *strstr(char *str1, char *str2);
功能:从字符串str1中查找是否有字符串str2,如果有,从str1中的str2位置起,返回str1中str2起始位置的指针,如果没有,返回null。
     如果s2为空串,则返回s1
返回值:返回该位置的指针,如找不到,返回空指针。
*/

#include <stdio.h>
//Copyright 1986 - 1999 IAR Systems. All rights reservedchar *strstr(const char *s1, const char *s2){int n;if (*s2){//s2不是空字符串while(*s1){//开始遍历s1for(n=0; *(s1+n) == *(s2+n); n++){if (!*(s2+n+1)){//如果n值为s2的长度,说明s2是s1的字串return (char*)s1;}}s1++; //没有找到,指针下移}return NULL;   //s2不是s1的字串}return (char*)s1;//s2为空串,返回s1}void find_str(char const* str, char const* substr) {    char* pos = strstr(str, substr);    if(pos) {        printf("found the string '%s' in '%s' at position: %d\n", substr, str, pos - str);    } else {        printf("the string '%s' was not found in '%s'\n", substr, str);    }} int main(int argc, char* argv[]) {    char* str = "one two three";    find_str(str, "two");    find_str(str, "");    find_str(str, "nine");    find_str(str, "n");      return 0;}


 

1.Copyright 1990 Software Development Systems, Inc.char *strstr( const char *s1, const char *s2 ){ int len2; if ( !(len2 = strlen(s2)) ) return (char *)s1; for ( ; *s1; ++s1 ) {    if ( *s1 == *s2 && strncmp( s1, s2, len2 )==0 )   return (char *)s1; } return NULL;}


 

 

GCC-4.8.0char * strstr (const char *s1, const char *s2) {   const char *p = s1;     const size_t len = strlen (s2);   for (; (p = strchr (p, *s2)) != 0; p++)   {     if (strncmp (p, s2, len) == 0)     return (char *)p;    }      return (0); }


 

 

char *strstr(char *s1 , char *s2){  if(*s1==0)  {    if(*s2) return(char*)NULL;    return (char*)s1;  }  while(*s1)  {    int i=0;    while(1)    {      if(s2[i]==0) return s1;      if(s2[i]!=s1[i]) break;      i++;    }    s1++;  }  return (char*)NULL;}


 

//linux源码#ifndef __HAVE_ARCH_STRSTR   /**  * 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)  {      size_t 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;  }  EXPORT_SYMBOL(strstr);  #endif  

原创粉丝点击