By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,204 Members | 1,161 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,204 IT Pros & Developers. It's quick & easy.

string match function

P: 11
in C, write a function [char *strmatch(char *str, char *s)]
which will find the first occurance of the string s in the string str and will return a pointer to the first match if such a match occurs. if there is no match, then strmatch() should return NULL

Here is what i came up with. am i close?

char *strmatch(char *str, char *s)
while (char *str != '\0'){

if (*str == *s){
return (*s);
return (NULL);
Sep 14 '06 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,916

Correcting your code so it would at least compile

Expand|Select|Wrap|Line Numbers
  1. char *strmatch(char *str, char *s){
  3.   while (char *str != '\0'){
  5.     if (*str == *s){
  6.       return (s);  // Note can't return *s that has type char
  7.       *s++;
  8.     }
  9.   }
  11.   return (NULL);
  12. }
Lets take an example

strmatch("Hello", "Help");

Help does not occur in Hello so NULL should be returned

At the while *str == 'H' so the loop continues
At the if *str == 'H', *s == 'H' so *str == *s and we enter the if block
In the if block return s pointer to "Help"

Function fails

Try another example

strmatch("Red dog eats meat", "dog");

This should return a pointer to "dog eats meat".

At the while *str == 'R' so the loop continues
At the if *str == 'R', *s == 'd' so *str!== *s and we don't enter the if block

There are no other statements so the while loop iterates and we start again

At the while *str == 'R' so the loop continues
At the if *str == 'R', *s == 'd' so *str!== *s and we don't enter the if block

this is exactly the same as the previous itteration because str and s are not changed, if fact the function has entered an infinite loop.

The behaviour of this function is

If the first characters match return a pointer to the string to search for else enter an infinite loop.

When writing a small simple function like this then trying a few test examples can easily prove or disprove the function, especially if you have a symbolic debugger to let you step through the code. Even if you don't have a symbolic debugger use of printf statements will help you work out what is going on.
Sep 15 '06 #2

P: 11
you're the greatest. thank you.
Sep 15 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.