About C language function STRSTR of analysis and implementation
- 2020-04-02 01:07:46
- OfStack
Prototype: char * STRSTR (const char *str1, const char *str2);
# include < String. H >
Find out where the str2 string first appears in the str1 string (not including the str2 string terminator). Returns a pointer to the location, if not found, returns a null pointer.
Returns a pointer to the first occurrence of strSearch in STR, or NULL if strSearch does not appear in STR. IfstrSearch points to a string of zero length, the function Returns STR.
Another implementation:
Another implementation:
# include < String. H >
Find out where the str2 string first appears in the str1 string (not including the str2 string terminator). Returns a pointer to the location, if not found, returns a null pointer.
Returns a pointer to the first occurrence of strSearch in STR, or NULL if strSearch does not appear in STR. IfstrSearch points to a string of zero length, the function Returns STR.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#pragma warning (disable:4996)
char *mystrstr(char *s1,char *s2);
int main(void)
{
char *s="Golden Global View";
char *l="ob"; //char *l=""
char *p;
system("cls");
p=mystrstr(s,l);
if (p!=NULL)
{
printf("%sn",p);
}
else
{
printf("Not Found!n");
}
getch();
return 0;
}
char *mystrstr(char *s1,char *s2)
{
int n;
if (*s2) //So there's two scenarios
{
while(*s1)
{
for (n=0;*(s1+n)==*(s2+n);n++)
{
if (!*(s2+n+1)) //Find whether the next character is '0'
{
return (char*)s1;
}
}
s1++;
}
return NULL;
}
else
{
return (char*)s1;
}
}
Another implementation:
char * strstr (buf, sub)
register char *buf;
register char *sub;
{
register char *bp;
register char *sp;
if (!*sub)
return buf;
while (*buf)
{
bp = buf;
sp = sub;
do {
if (!*sp)
return buf;
} while (*bp++ == *sp++);
buf += 1;
}
return 0;
}
Another implementation:
#include <iostream>
#include <string>
using namespace std;
//C language implementation STRSTR
const char* isSub(const char* str, const char *subs){
//A special case
if(!*subs)
return str;
const char* tmp=str;
while (*tmp!='0')
{
//Used to move the parent string backward one character at a time
const char* tmp1=tmp;
//Record the substring address
const char* sub1=subs;
while (*sub1!='0'&&*tmp1!='0')
{
//If it is not equal, it jumps out and moves the parent string back one character
if (*sub1!=*tmp1)
break;
//If the substring is equal and the next character in the substring is the end, then it is a substring of the parent string
if (*sub1==*tmp1&&*(sub1+1)=='0')
return tmp;
//If equal, continue to compare the next character
if (*sub1==*tmp1)
{
sub1++;
tmp1++;
}
}
tmp++;
}
return NULL;
}
int main(){
char* str1="ababcdddb";
char* str="";
const char *res=isSub(str1,str);
if (res!=NULL)
{
cout << res << endl;
}
else
cout << "null" << endl;
//cout << isSub(str1,str) << endl;
return 0;
}