MathGroup Archive 2004

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

Search the Archive

Re: trimming a string


here is my version:

      While[StringMatchQ[trimmed," *"],trimmed=StringDrop[trimmed,1]];
      While[StringMatchQ[trimmed,"* "],trimmed=StringDrop[trimmed,-1]];
trimString["  a b "]

I hoped can be done in one line...

Akos Beleznay

-----Original Message-----
From: Wolf, Hartmut [mailto:Hartmut.Wolf at] 
To: mathgroup at
Subject: [mg50871] Re: [mg50861] trimming a string

I forgot the check for the most simple case; we have to bail out then

trimString[str_] := Module[{p = StringPosition[str, " "], s, t, u},
    If[p === {}, Return[str]];
    t = Transpose[p][[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, _} | {_,

In[18]:= trimString["xxxx"]
Out[18]= "xxxx"


>-----Original Message-----
>From: Wolf, Hartmut 
To: mathgroup at
>Sent: Friday, September 24, 2004 3:28 PM
>To: 'Akos Beleznay'; mathgroup at
>Subject: [mg50871] RE: [mg50861] trimming a string
>>-----Original Message-----
>>From: Akos Beleznay [mailto:abeleznay at]
To: mathgroup at
>>Sent: Friday, September 24, 2004 10:42 AM
>>To: mathgroup at
>>Subject: [mg50871] [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, _} | {_, 
>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)

This email is intended for the sole use of the intended recipient(s) and may contain confidential or privileged information. No one is authorized to copy or re-use this email or any information contained in it. If you are not the intended recipient, we request that you please notify us by reply email and destroy all copies of the message and any attachments. PAFA reserves the right to monitor and review the content of all e-mail communications sent and/or received by its affiliates. Thank you for your cooperation.

  • Prev by Date: Re: Programing operations with lists
  • Next by Date: Re: Programing operations with lists
  • Previous by thread: Re: trimming a string
  • Next by thread: Re: Re: trimming a string