MathGroup Archive 2005

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

Search the Archive

Re: partitioning a string

  • To: mathgroup at smc.vnet.net
  • Subject: [mg60966] Re: partitioning a string
  • From: Peter Pein <petsie at dordos.net>
  • Date: Wed, 5 Oct 2005 02:28:12 -0400 (EDT)
  • References: <dht45r$hks$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Sara schrieb:
> I have tred to partition a String and iwrote this code but its take to time to run, and it doesnt show eny result.
> stringPartition[s_, n_] := Module[{}, emptyString = Mod[StringLength[s], n];
>     If[emptyString != 0, empt = n - emptyString];
>     str1 := " ";
>     str2 := "";
>     For[i = 1, i <= empt, i++, str2 = str2 <> str1];
>     str = s <> str2;
>     M = StringLength[str];
>     yasList = Range[1, M/n] ; 
>     For[i = 1, i <= M, i + n, For[j = 1, j <= M/n, j++,
>           yasList[[j]] = StringTake[i, j*n]
>                ];
>            ];
> 
Hi Sara,

1.) even if the closing "]" from Module would be there, your function 
would return Null, because the nested For ends with a semicolon.
2.) empt will be uninitialized, when emptyString==0 and the first For 
will fail.
3.) in general: do not use variable names starting with a capital letter 
(M in this case). They are commonly used for function names (like N).
4.) the statement i+n should become the assignment i+=n or i=i+n.
5.) I guess StringTake[i,j] should read StringTake[str,[i,j}]?
6.) you assign values to a global variable yasList ("yet another 
string"?) but don't use them.

b.t.w.: if you are using Module it would be a great idea to declare all 
local variables as local ;-)

It would have been easier, to construct a list of the characters of s, 
partition this list and reassemble the strings. If I interpret your code 
correctly, you want to append spaces to your string until its length is 
a multiple of n.

stringPartition[s_,n_]:=
   StringJoin @@@ Partition[Characters[s], n, n, {1, 1}, {" "}]

please see the documetation for details about Partition.

stringPartition["A string", 3] // InputForm
gives:
   {"A S", "tri", "ng "}

Peter


  • Prev by Date: Re: Pure Function for String Selection
  • Next by Date: Re: Re: Help with output form?
  • Previous by thread: Re: partitioning a string
  • Next by thread: Partition(divid string to substring