问题
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?
回答1:
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.
回答2:
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.
回答3:
f[n_] := StringJoin[Table[" ", {n}]]
回答4:
Spacer
and Invisible
are also be useful for creating whitespace, with differences in how you specify the size of the space.
回答5:
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]
来源:https://stackoverflow.com/questions/6082172/creating-a-variable-length-string-of-whitespaces-in-mathematica