A Journey 2 Eternity

Implement strstr() to find a substring in a string

Posted on: August 1, 2012

char* StrStr(const char *str, const char *target) 
{
	char *cp = (char *) str;
	char *s1, *s2;

	if ( !*target ) {
		return ((char *)str);
	}

	while (*cp)
	{
		s1 = cp;
		s2 = (char *) target;

		while ( *s1 && *s2 && (*s1 == *s2) ) {
			++s1;
			++s2;
		}

		if (!*s2) {
			return cp;
		}

		++cp;
	}

	return NULL;
}
Advertisements
Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

August 2012
M T W T F S S
« Jul    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 27,085 hits
%d bloggers like this: