How trim?

Ken Ray kray at sonsothunder.com
Sat Oct 22 21:17:05 EDT 2005


On 10/22/05 4:51 PM, "Alex Tweedly" <alex at tweedly.net> wrote:

> Bob Warren wrote:
> 
>> 
>> Alex:
>> 
>> I couldn't seem to make your first suggestions for L and R trims work.
>> Would you mind spelling out some example routines for me?
> 
> I've combined Mark Smith's versions, an alternate for one of his and
> mine all in the following script.
> Beware there are subtle differences in the results from the various
> solutions presented (these here, and Thomas's regex-based ones).
> 
> The original question actually said "remove blanks", and mentioned the
> LTRIM$ etc. functions in Basic.
> 
> In VB (I believe), LTRIM removes *only* spaces.
> In other versions of Basics (and also in PHP, Python, Perl, etc.) Ltrim
> (or equivalents) remove all whitespace characters (usually, spaces and
> TABs).
> 
> So if that subtle difference matters, be careful which one you use.

Also one other thing to keep in mind - if you're going to be doing full
trimming (i.e. *all* white spaces - space, tab, 'hard' (non-breaking)
spaces, CRs, LFs, etc.) and you're going be doing it in a repeat loop,
you're going to want the most efficient version available.

Originally I proposed using matchText to make this happen:

function trim pWhat
  local tRetVal
  get matchText(pWhat, "(?s)^\s*(.*?)\s*$", tRetVal)
  return tRetVal
end trim

But when using RevBench (Richard Gaskin's benchmarking tool), it was 74x
slower than using Jacque's original suggestion which did everything *but*
hard spaces:

function Trim what
  return (word 1 to -1 of what)
end Trim

So this next version is the fastest approach I've found that accommodates
everything:

function Trim what
  if the platform is "MacOS" then
    replace numToChar(202) with " " in what
  else
    replace numToChar(160) with " " in what
  end if
  return (word 1 to -1 of what)
end Trim

Here's the benchmarks (tested over 50000 loops):

Trim (matchtext): 0.0148 ticks/run
Trim (word 1 to -1, no hard space):  0.0002 ticks/run
Trim (word 1 to -1, gets everything): 0.0004 ticks/run

Just FYI...


Ken Ray
Sons of Thunder Software
Web site: http://www.sonsothunder.com/
Email: kray at sonsothunder.com




More information about the use-livecode mailing list