Creating a variable-length string of spaces in Mathematica

The following Mathematica f function creates a string of spaces of length n.

f[n_]:=Fold[StringJoin,"",Array[" "&,n]]

There must be many alternatives to create this function.

How would you do that?

+5
source share
5 answers
f[n_] := StringJoin @ ConstantArray[" ", n]

Edit: since @ is just as idiomatic as @@, and a little faster (thanks to Mr.Wizard for benchmarking) and in short I updated the solution.

+10
source
f[n_] := FromCharacterCode[ConstantArray[32, {n}]]

By the way: you should know that this type of question is not approved in faq :

What questions can I not ask here?

, , , . , . , , , , ...

1. every answer is equally valid: "What’s your favorite ______?"

, .

+5
f[n_] := StringJoin[Table[" ", {n}]]
+3

Spacer Invisible , , .

+2
f = ConstantArray[" ", #] <> "" &;

, Thies Heidecke,, , Sjoerd's.


n . , Sjoerd n > 10000:

f2ss = " "~ConstantArray~499 <> "";
f2[n_ /; n < 500] := StringTake[f2ss, n]
f2[n_ /; n < 5000] := StringTake[ConstantArray["          ", ⌈n/10⌉] <> "", n]
f2[n_] := StringTake[ConstantArray[f2@400, ⌈n/400⌉] <> "", n]
+2

All Articles