Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: trimming a string

  • To: mathgroup at
  • Subject: [mg50868] Re: [mg50861] trimming a string
  • From: "Wolf, Hartmut" <Hartmut.Wolf at>
  • Date: Sat, 25 Sep 2004 01:55:06 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

>-----Original Message-----
>From: Akos Beleznay [mailto:abeleznay at]
To: mathgroup at
>Sent: Friday, September 24, 2004 10:42 AM
>To: mathgroup at
>Subject: [mg50868] [mg50861] trimming a string
>I would appreciate if somebody could show me a simple way of trimming a
>string. (I did it a hard way, but suspect an elegant solution.)
>Trim(a_string): returns a copy of a string without leading and trailing
>Akos Beleznay


I don't your solution, but here is another one, striktly unelegant:

trimString[str_] := 
  Module[{s, t, u}, t = Transpose[StringPosition[str, " "]][[1]];
    s = t - Join[{0}, Drop[t, -1] + 1];
    u = #[[{1, -1}, 2]] & /@ Split[Transpose[{s, t}], First[#2] == 0 &];
    Fold[StringDrop, str, Reverse@Cases[u, {1, _} | {_, StringLength[str]}]]]

In[81]:= ss = "In the beginning there was no earth or sky";

In[82]:= ss === trimString[ss]
Out[82]= True
In[83]:= ss === trimString[StringJoin["  ", ss]]
Out[83]= True
In[84]:= ss === trimString[StringJoin[ss, " "]]
Out[84]= True

(But possibly, for string manipulation, you might like to search for a different tool, Perl perhaps)


  • Prev by Date: Re: trimming a string
  • Next by Date: Minimization problem
  • Previous by thread: Re: Re: trimming a string
  • Next by thread: Re: trimming a string