What is an appropriate command that does the opposite of the following?
StringSplit["a b c d e f g"," "]
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityA combination of StringJoin
and Riffle
:
res = StringSplit["a b c d e f g"," "];
StringJoin@Riffle[res," "]
StringSplit[" a b c "," "]
is just {"a", "b", "c"}
so information is lost. There is no way you could know if there were a leading or ending space in the original string. This is the closest to an inverse that you can come. In Javascript that information is preserved by split
.
$\endgroup$
StringSplit[" a b c ", " ", All]
.
$\endgroup$
In version 10.1 you can use StringRiffle
:
res = StringSplit["a b c d e f g", " "];
StringRiffle[res]
Use no second argument for spaces, or something else for something else. A nice advantage of StringRiffle
is that res
elements can be non string elements, and it will be automatically converted. It's something I miss in StringJoin
.
PS: this answer is based on Docs, I don't have V10.1.
Take care with ToString@Row
in V9 or older. See this post, about some problems.
" a b ".split(" ").join(" ")
"
$\endgroup$
Sometimes you can you this alternative:
res = StringSplit["a b c d e f g", " "];
ToString @ Row[res, " "]
I know, I know, Kuba's and Pickett's solutions are preferable. For those who fancy Patterns here is an alternative.
StringReplace[res, t : __ :> t <> " "] // StringJoin // #~StringDrop~ -1 &
Doesn't look elegant, anyhow.....it works...hi,hi,hi.!
res = StringSplit["a b c d e f g", " "];
Fold[#1 <> " " <> #2 &, res]
(*"a b c d e f g"*)
res = StringSplit[s = " a b c d e f g ", " "]; StringJoin@Riffle[res, " "]; % == s
will be False... fails with trailing spaces also. Don't think one can correctly reconstruct all stings from a string split... $\endgroup$s
, is it... bottom line, there is no direct inverse for the title form for all strings. $\endgroup$All
as the optional third argument to the split allows correct reconstruction of all strings, but then you will have the "excess" (any leading/trailing/adjacent whitespace) as members of the split. $\endgroup$