strstr和strrstr已经算是字符串中相对比较难的了,但是只要我们善于分析,解剖字符串,就会化难为易。其实学习代码的过程中需要我们静下心来分析,理解。

srtstr函数的功能及用法

原型:char *strstr(const char *dst, const char *src);

#include<string.h>

找出src字符串在dst字符串中第一次出现的位置(不包括src的串结束符)。返回该位置的指针,如找不到,返回空指针。

代码:

#include<stdio.h>#include<string.h>#include<assert.h>char*my_strstr(constchar*dst,constchar*src){constchar*str1=dst;constchar*str2=src;constchar*fast=NULL;assert(dst);assert(src);while(*str1){fast=str1;while(*str1&&*str2&&*str1==*str2){str1++;str2++;}if(*str2=='\0')return(char*)fast;str1=fast+1;str2=src;}returnNULL;}intmain(){chararr1[]="abcdefgdefk";chararr2[]="defk";char*ret=my_strstr(arr1,arr2);if(*ret){puts(ret);}return0;}

解析代码:

在main函数中定义两个字符串数组,char arr1[]="abcdefgdefk";char arr2[]="defk";在调用函数中用指针来接收,指针接收的优点是指针指向字符串的首地址,指针最好用const保护起来,以防被破坏。在调用函数中定义三个指针,char *sr1=dst,char* str2=src,char* fast=NULL(避免野指针),使用之前先断言指针是否存在,如果str1的内容存在进入循环,先将fsat=str1;如果str1指向的内容等于str2指向的内容,str1,str2的地址加加,如果str2的内容等于"\0"了,说明str2字符串的内容在str1字符串中出现,否则str1指向fast指针指向地址的后一个地址,str2返回到它的首地址,继续执行循环直到str2字符串在str1中第一次出现。

模拟实现strrstr函数

原型:char *strrstr(const char *str1, const char *str2);

#include<string.h>

找出str2字符串在str1字符串中最后出现的位置(不包括str2的串结束符)。返回该位置的指针,如找不到,返回空指针。

#include<stdio.h>#include<string.h>#include<assert.h>char*my_strrstr(constchar*dst,constchar*src){char*str1=dst;char*str2=src;char*fast=NULL;char*last=NULL;assert(dst);assert(src);while(*str1){fast=str1;while(*str1&&*str2&&*str1==*str2){str1++;str2++;}if(*str2=='\0')last=fast;str1=fast+1;str2=src;}if(*str1=='\0')return/*(char*)*/last;/*returnNULL;*/}intmain(){char*Qwe="asdfghasdgfdfgdfgdfgdfgdfg";char*Zaq="dfg";char*ret=my_strrstr(Qwe,Zaq);puts(ret);return0;}