What is an appropriate command that does the opposite of the following?
StringSplit["a b c d e f g"," "]
What is an appropriate command that does the opposite of the following?
StringSplit["a b c d e f g"," "]
A combination of StringJoin and Riffle:
res = StringSplit["a b c d e f g"," "];
StringJoin@Riffle[res," "]
" a b ".split(" ").join(" ")
– William
Mar 27 '15 at 22:46
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.
– C. E.
Mar 27 '15 at 23:44
StringSplit[" a b c ", " ", All].
– C. E.
Mar 27 '15 at 23:48
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(" ")
"
– William
Mar 27 '15 at 22:47
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, " "]; % == swill be False... fails with trailing spaces also. Don't think one can correctly reconstruct all stings from a string split... – ciao Mar 27 '15 at 22:34s, is it... bottom line, there is no direct inverse for the title form for all strings. – ciao Mar 27 '15 at 22:39Allas 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. – ciao Mar 27 '15 at 23:04