Creating a variable length string of whitespaces i

2019-06-23 17:10发布

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?

5条回答
萌系小妹纸
2楼-- · 2019-06-23 17:57
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]
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-23 18:00
f[n_] := StringJoin[Table[" ", {n}]]
查看更多
成全新的幸福
4楼-- · 2019-06-23 18:01
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.

查看更多
贼婆χ
5楼-- · 2019-06-23 18:08

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

查看更多
Explosion°爆炸
6楼-- · 2019-06-23 18:14
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.

查看更多
登录 后发表回答