Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Trimming Whitespaces

Options
  • 23-06-2005 10:44am
    #1
    Closed Accounts Posts: 139 ✭✭


    have a bit of c code that is ment to take a string (that may or may not have spaces before or after the string) i.e. " stuff ", and trims off the whitespace before and after.
    Code:

    char *trim (char *str, char ch)
    {
    char *first, *last;
    int count;

    /* Move first to the first character that isn't the same as ch */
    for (first = str; *first == ch; first++);
    /* Move last to the null character. Thats the only way to know 100% we are
    * removing items from the end of the string */
    for (last = first; *last != '\0'; last++);
    /* Ok now we backtrack until we find a character that isn't the same as ch */
    for (last--; *last == ch; last--);

    if ( first != str)
    {
    for (count=0; count< last - first + 1; count++)
    str[count] = *(first+count);
    str[count] = '\0';
    }
    else
    {
    str[last-first] = '\0';
    }

    return str;
    }

    the problem is that it always removes the last letter of str as well. i.e.
    " stuff " -> "stuf" any ideas why this is happening.
    Cheers
    John


Comments

  • Registered Users Posts: 7,276 ✭✭✭kenmc




  • Registered Users Posts: 441 ✭✭robfitz


    The problem with your code is in this line:
    john_g83 wrote:
    {
    str[last-first] = '\0';
    }

    last points to the last non-ch character, but it needs to be the last ch character or '\0', change it to "str[last-first+1] = '\0';".


  • Closed Accounts Posts: 139 ✭✭john_g83


    :) thanks ken, that was EXACTLY what I was looking for, was able to implement that into my code very easily...that's saved me alot of hastle..you the man.

    looking at it again, what you have suggested rob would also work, thanks very much


Advertisement