Is there a way to write down Mathematica
with a string such as:
{"M","a","t","h","e","m","a","t","i","c","a"}
?
7 Answers
Supporting the maxim "there is always another way to do it":
list = {"M","a","t","h","e","m","a","t","i","c","a"};
StringJoin
accepts lists directly, and in fact is faster this way:
StringJoin @ list
"Mathematica"
Also, StringJoin
has the short form <>
therefore you could also use:
"" <> list
"Mathematica"
Speed check:
large = Characters@ExampleData[{"Text", "LoremIpsum"}];
Do[StringJoin @@ large, {5000}] // Timing
Do[StringJoin @ large, {5000}] // Timing
Do["" <> large, {5000}] // Timing
Version 7.0.1 timings:
{1.622, Null} {0.702, Null} {0.718, Null}
Version 10.1.0 timings:
{0.6864, Null} {0.4524, Null} {0.4524, Null}
-
$\begingroup$ Good maxim :) You and Jagra seem to have the same one :) $\endgroup$– ÖskåJun 19, 2012 at 19:21
-
3
-
-
-
1$\begingroup$ It's a shame that you give the nice answer
StringJoin @ list
, but then use the not-so-nice answerStringJoin @@ list
in your speed comparison. $\endgroup$ Oct 10, 2019 at 19:56
Just for something different Fold
works too:
Fold[#1 <> #2 &, "", {"M", "a", "t", "h", "e", "m", "a", "t", "i",
"c", "a"}]
"Mathematica"
Use StringJoin
:
StringJoin @@ {"M", "a", "t", "h", "e", "m", "a", "t", "i", "c", "a"}
"Mathematica"
-
$\begingroup$ ah, been looking for one hour. Feels dumb Thanks! $\endgroup$– ÖskåJun 19, 2012 at 18:41
-
3$\begingroup$ No problem, we've all experienced the same thing, good luck. $\endgroup$ Jun 19, 2012 at 18:42
If we're going to get silly about it:
TextRecognize @ Graphics @ MapIndexed[Text[Style[#1, 50], {#2[[1]], 0}] &, list]
At risk of taking "even more" too far here is a method that does not use any function with "String" in the name:
list = {"M", "a", "t", "h", "e", "m", "a", "t", "i", "c", "a"};
FromCharacterCode @ Flatten @ ToCharacterCode @ list
Or using an export function:
ExportString[{list}, "Table", "FieldSeparators" -> ""]
Or a formatting function:
ToString @ Row @ list
-
$\begingroup$ Sheer vulpinism, that's what it is :) $\endgroup$ Jun 19, 2012 at 21:37
-
$\begingroup$ +1 for: 'ToString @ Row @ list'. This seems to me the most interesting of all the solutions offered for the question, because you've taken such an original view of the problem while maintaing your customary clarity and conciseness. Nice! $\endgroup$– JagraJun 20, 2012 at 14:03
Just to stretch even more the limits of "there is always another way to do it" (Mr.Wizard), here is a way to NOT use StringJoin
at all:
chars = {"M", "a", "t", "h", "e", "m", "a", "t", "i", "c", "a"};
Fold[StringInsert[#1, #2, -1] &, "", Flatten@chars]
"Mathematica"
And a simpler one:
StringExpression @@ chars
Using built-in path functions to complicate things (use ToFileName
if prior to version 7):
StringReplace[FileNameJoin@chars, "\\" -> ""]
?*String*
will list the available string functions if you need more information. $\endgroup$