This is how I would write the standard library function strstr if I had to implement it from scratch.
strstr implementation from scratch
#include <iostream>
const char *mystrstr(const char *p, const char *q);
int main()
{
char t1[256] = {0};
char t2[256] = {0};
std::cout << "Enter a string: ";
std::cin.getline(t1, 256);
std::cout << "Search for: ";
std::cin.getline(t2, 256);
if( const char *p = mystrstr(t1, t2) )
std::cout << "Found: " << p << std::endl;
else
std::cout << "Not found!" << std::endl;
return 0;
}
const char *mystrstr(const char *p, const char *q)
{
for( ; *p; ++p)
{
const char *p_tmp = p;
const char *q_tmp = q;
for( ; *p_tmp == *q_tmp && *q_tmp; ++p_tmp, ++q_tmp);
if( !*q_tmp ) return p;
}
return 0;
}
/* Sample run:
Enter a string: Hello World
Search for: Wo
Found: World
Enter a string: Hi Daniweb!
Search for: Hill
Not found!
*/
tux4life 2,072 Postaholic
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.