string match function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jmprince01
    New Member
    • Sep 2006
    • 11

    #1

    string match function

    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);
    *s++;
    }
    }
    return (NULL);
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    No

    Correcting your code so it would at least compile

    Code:
    char *strmatch(char *str, char *s){
    
      while (char *str != '\0'){
    
        if (*str == *s){
          return (s);  // Note can't return *s that has type char
          *s++;
        }
      }
    
      return (NULL);
    }
    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.

    Comment

    • jmprince01
      New Member
      • Sep 2006
      • 11

      #3
      you're the greatest. thank you.

      Comment

      Working...