C++中strstr函數(shù)的實現(xiàn)方法總結(jié)
C++中strstr函數(shù)的實現(xiàn)方法總結(jié)
函數(shù)說明:
包含文件:string.h
函數(shù)名: strstr
函數(shù)原型:extern char *strstr(char *str1, char *str2);
功能:從字符串str1中查找是否有字符串str2, 如果有,從str1中的str2位置起,返回str1的指針,如果沒有,返回null。
返回值:返回該位置的指針,如找不到,返回空指針。
方法一:
#include <iostream>
#include <assert.h>
using namespace std;
char* My_strstr(char *src,char *substr)
{
assert(src != NULL && substr != NULL);
unsigned int size = strlen(src);
for(int i = 0; i < size; ++i,++src)
{
char *p = src;
for(char *q = substr;;p++,q++)
{
if(*q == '\0') //在src中找到連續(xù)的substr子串停止并返回
{
return src;
}
if(*q != *p)
{
break;
}
}
}
return NULL;
}
int main()
{
char *res = My_strstr("abcdefg","cde");
if(res != NULL)
{
cout<<"exist:"<<res<<endl;
}
else
{
cout<<"no exist!"<<endl;
}
return 0;
}
方法二:
#include <iostream>
#include <assert.h>
using namespace std;
char* My_strstr(const char* s1,const char* s2)
{
int n;
if(*s2)
{
while(*s1)
{
for(n=0;*(s1+n)==*(s2+n);n++)
{
if(!*(s2+n+1))
return (char*)s1;
}
s1++;
}
return NULL;
}
else
return (char*)s1;
}
int main()
{
char *res = My_strstr("abcdefg","cde");
if(res != NULL)
{
cout<<"exist:"<<res<<endl;
}
else
{
cout<<"no exist!"<<endl;
}
return 0;
}
方法三:
#include <iostream>
#include <assert.h>
using namespace std;
char* My_strstr(const char* s1,const char* s2)
{
const char *p=s1;
const size_t len=strlen(s2);
for(;(p=strchr(p,*s2))!=0;p++)// strchr查找字符串s中首次出現(xiàn)字符c的位置
{
if(strncmp(p,s2,len)==0)
{
return(char*)p;
}
}
return(0);
}
int main()
{
char *res = My_strstr("abcdefg","cde");
if(res != NULL)
{
cout<<"exist:"<<res<<endl;
}
else
{
cout<<"no exist!"<<endl;
}
return 0;
}
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C++ 手把手教你實現(xiàn)可變長的數(shù)組實現(xiàn)
這篇文章主要介紹了C++ 手把手教你實現(xiàn)可變長的數(shù)組實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
詳解C++中如何將構(gòu)造函數(shù)或析構(gòu)函數(shù)的訪問權(quán)限定為private
這篇文章主要介紹了詳解C++中如何將構(gòu)造函數(shù)或析構(gòu)函數(shù)的訪問權(quán)限定為private的方法,文中還解釋了構(gòu)造函數(shù)與虛函數(shù)的區(qū)別,需要的朋友可以參考下2016-03-03
C語言數(shù)據(jù)結(jié)構(gòu)超詳細(xì)講解單向鏈表
鏈表可以說是一種最為基礎(chǔ)的數(shù)據(jù)結(jié)構(gòu)了,而單向鏈表更是基礎(chǔ)中的基礎(chǔ)。鏈表是由一組元素以特定的順序組合或鏈接在一起的,不同元素之間在邏輯上相鄰,但是在物理上并不一定相鄰。在維護(hù)一組數(shù)據(jù)集合時,就可以使用鏈表,這一點和數(shù)組很相似2022-03-03
Cocos2d-x學(xué)習(xí)筆記之開發(fā)環(huán)境搭建
這篇文章主要介紹了Cocos2d-x學(xué)習(xí)筆記之開發(fā)環(huán)境搭建,本文使用Visual Studio作為開發(fā)IDE,是不同于其它教程的,需要的朋友可以參考下2014-09-09

