C/string and charecter manipulation using strings
Expert: Joseph Moore - 9/20/2009
Questioni have to work on two functions one to replace and another one to match strings using pointers.
char *strmatch(char *str, char *s)
so if *str was: "Hello my name is Nick."
and *s was: "my n"
strmatch would output:ame is Nick.
if nothing is matched strmatch would output null. I need to use a driver.c to read in the two lines from stdin using fgets.
I have little to no idea on how to go about starting this so any help would be appreciated.
AnswerHi, Nick.
I generally prefer not to just give code, but I'm a little tired right now and it's easier to just write the function than to try to go over it all in English... I think I may speak C/C++ better than I do English these days, and my mom's an English professor! :) Below, you will find the code for the strmatch function. I've commented it extensively so you can understand why I've done what I've done. I will say that the basic idea is to set up a double loop: an outer loop which iterates through each character in the original string, and an inner loop which compares and iterates through the remaining characters in the string and the search string. You'll see this demonstrated in the code below. Look it over, and if you have any questions, please do not hesitate to ask.
#include <stdio.h>
char* strmatch(char* _str, char* _match)
{
// Set up the variable we're going to use in our loop,
// then loop until a NULL terminator character is found.
// (The NULL terminator, '\0', has a value of 0, hence,
// false.)
char* pCurLoc = _str;
while (*pCurLoc)
{
// We need a sub loop that loops on both strings, so
// here we set up the two variables to loop through
// the sub string and the match string.
char* pSubStrPos = pCurLoc;
char* pMatchLoc = _match;
// As long as the current characters are the same,
// we need to continue looping.
while (*pSubStrPos == *pMatchLoc)
{
// Increment the position of both strings.
++pSubStrPos;
++pMatchLoc;
// Check for the end of the match string, indicating
// a full, positive match. Then return the current
// sub string position.
if (*pMatchLoc == '\0')
return pSubStrPos;
}
// Increment the current string position
++pCurLoc;
}
// No match
return NULL;
}
void main()
{
char* str1 = "This is string one.";
char* strMatch = "is str";
printf("%s\n", strmatch(str1, strMatch));
}