Re: Trimming whitespaces



john_g83@xxxxxxxxxxx wrote:
>
> 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)

Untested:

char *trim(char *s, char ch)
{
char *p;

if (s && *s && ch) { /* avoid evil cases */
while (ch == *s) s++; /* trims leading. */
p = s; /* must be advanced over entry */
while (*p) p++; /* find end of string */
p-- /* last char in string */
while ((p > s) && (ch == *p)) p--;
*p = '\0';
}
return s; /* ok in evil cases */
}

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson


.



Relevant Pages

  • Re: Fast string operations
    ... the char[] for each string cached with the string, or is a new one created ... the string is full of whitespace. ... >> ToLowergenerates a new string instance as does Trim. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: How to add thousand separators
    ... First, this code is obsolete as written, because char is a dead data type and should not ... Note that both of these should be stored as string resources since they might need to be ... 18 digits for any reason. ... you have made a VERY SERIOUS DESIGN ERROR. ...
    (microsoft.public.vc.mfc)
  • Re: Returning a character buffer from a DLL
    ... I need to return a string buffer from the DLL in a RunQuery function. ... I find it odd that you are using the obsolete 'char *' data type here. ... want to use a string pointer of any type here! ...
    (microsoft.public.vc.mfc)
  • Re: what is the best way of passing floats into a string
    ... I do not null-terminate as snprintf takes care of this (according to ... But the easiest way to determine the size needed to format a number, ... int length_of_representation(double n,const char* format){ ... I get a nice result of -10.000000 in my char * string. ...
    (comp.unix.programmer)
  • Re: weird problem
    ... I already told you that the comparison between an integer and a float ... to strcmpwhich expects a pointer to a string. ... And now a question about something else: why do you use floating ... int,float, char, etc. ...
    (comp.lang.c)