Re: Errors in function trim() (ESL0.01)
- Posted by Juergen Luethje <j.lue at gmx.de> Mar 28, 2006
- 455 views
Pete Lomax wrote: > On Sun, 26 Mar 2006 23:08:57 -0800, "Julio C. Galaret Viera" > <guest at RapidEuphoria.com> wrote: > >> I found errors both in syntax and algorithm in the trim() function >> (string.e). > <snip> > This should be faster (possibly by as much as a factor of 5, though in > most cases less) and does not crash when passed eg "" or " ": > }}} <eucode> > global function trim(sequence str) > -- > -- remove leading and trailing whitespace. > -- > integer slicestart, sliceend > slicestart=1 > sliceend=length(str) > while slicestart<=sliceend > and find(str[slicestart]," \t") do > slicestart += 1 > end while > while sliceend>slicestart > and find(str[sliceend]," \t") do > sliceend -= 1 > end while > -- avoid performing a slice unless we have to, since it > -- requires a mem alloc/copy; [improves performance] > if slicestart>1 or sliceend<length(str) then > return str[slicestart..sliceend] > end if > return str > end function > </eucode> {{{ I would replace " \t" with a variable, say 'charsToTrim', and then call the function like this:
global function trim_chars(sequence str, sequence charsToTrim) ... end function
So someone can use this function for removing leading and trailing dots or whatever. The normal trim() function then could be implemented like this:
constant WSP = " \t\r\n" global function trim(sequence str) return trim_chars(str, WSP) end function
Regards, Juergen -- Have you read a good program lately?