写一个函数,模拟strstr()函数

来源:互联网 发布:java格斗游戏佐罗 编辑:程序博客网 时间:2024/06/06 11:02

思路:

1 外层循环依次遍历长串,判断长串的某字符是否和短串的第一个字符相等

 2 如果相等,记录保存长串字符的位置,令temp=i,则长串和短串继续后移比较,直到短串到达末位,此时返回temp为起始地址的字符长串

否则将i=temp;继续进行外层循环

3外层循环遍历完都没找到,则返回NULL;

//写一个函数,模拟strstr()函数,strstr()函数主要将主串中子串
//以及以后的字符全部返回。比如主串是12345678,子串时234,那么返回2345678
#include<iostream>
using namespace std;
const char*strst1(const char* string,const char* strCharSet){
 for(int i=0;string[i]!='\0';i++){  //依次进行大串遍历
  int temp;
  temp=i;  //做标记和传递作用
  int j=0;
  while(string[i]==strCharSet[j]){
   i++;
   j++;
   if(strCharSet[j]=='\0'){
    return &string[temp]; //遍历比较完成,则返回起始位置到串尾的组成的串
   }

  }
  i=temp;
 }
 return NULL;
}
int main(){
 
 char*string="12345678";
 char strCharSet[10]={};
 cin>>strCharSet;   //输入如果大于等于10则,内存错误
 const char *p=strst1(string,strCharSet);
 if(p!=NULL){
  cout<<p<<endl;
 }
 else
  cout<<"no exist!"<<endl;
 return 0;
}

原创粉丝点击