nilo de roock
nilo de roock

Reputation: 4157

Creating a variable length string of whitespaces in Mathematica

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

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

There must be a zillion alternatives to create this function.

How would you have done it?

Upvotes: 5

Views: 524

Answers (5)

Mr.Wizard
Mr.Wizard

Reputation: 24336

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

This is about twice as fast as Thies Heidecke's function, but not nearly as fast as Sjoerd's.


For large n a longer initial string is helpful. This is faster than Sjoerd's method for 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]

Upvotes: 2

Thies Heidecke
Thies Heidecke

Reputation: 2537

f[n_] := StringJoin @ ConstantArray[" ", n]

Edit: since @ is as idiomatic as @@ and a bit faster (thanks to Mr.Wizard for benchmarking) and shorter i updated the solution.

Upvotes: 10

Brett Champion
Brett Champion

Reputation: 8577

Spacer and Invisible are also be useful for creating whitespace, with differences in how you specify the size of the space.

Upvotes: 2

Sjoerd C. de Vries
Sjoerd C. de Vries

Reputation: 16232

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

By the way: you should be aware that this type of question is frowned upon in the faq:

What kind of questions should I not ask here?

You should only ask practical, answerable questions based on actual problems that you face. Chatty, open-ended questions diminish the usefulness of our site and push other questions off the front page. To prevent your question from being flagged and possibly removed, avoid asking subjective questions where …

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

Don't be surprised if the question is closed.

Upvotes: 5

Bill White
Bill White

Reputation: 1789

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

Upvotes: 3

Related Questions