Answer the question
In order to leave comments, you need to log in
How to implement the search for one string in another in c++?
Since I am a beginner, I want to know how correct this solution is. Task: find the string for_search in the string string. What did I do wrong? How else can something like this be done? Thanks in advance for your replies.
int find_str(char *some, char *for_search){
char *p, *j;
for (int i = 0; some[i]; i++){
p = &some[i];
j = for_search;
while (*p == *j && *p != 0){
j++; p++;
}
if (!*j && (*p == ' ' || !*p)) return i;
else {
p = &some[i];
j = for_search;
}
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
Take the source of some CRT.
char * __cdecl strstr (
const char * str1,
const char * str2
)
{
char *cp = (char *) str1;
char *s1, *s2;
if ( !*str2 )
return((char *)str1);
while (*cp)
{
s1 = cp;
s2 = (char *) str2;
while ( *s1 && *s2 && !(*s1-*s2) )
s1++, s2++;
if (!*s2)
return(cp);
cp++;
}
return(NULL);
}
Ugly:
You increment the value of a pointer and then get a character from it for something. Right:
In general, you have implemented the simplest algorithm. The list of algorithms can be viewed here .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question