How to convert string to integer list?
For performance fiends:
I had an application that had this very need for some huge sets of long integer strings.
kguler's solution is certainly the canonical way, and quite quick, as is Felix's version (I was actually surprised on that one). eldo's solution is probably what most would come up with, but in performance-intensive scenarios the StringSplit
is a killer. This is what I use for integer string to digit list conversion:
toDigs=With[{s = Subtract[ToCharacterCode[#], 48]}, Pick[s, UnitStep@s, 1]]&;
(n.b.: If the integer string is sans spaces, just Subtract[ToCharacterCode[#], 48]&
suffices, with a nice speed bump.)
On large strings, the performance advantage can be orders of magnitude:
Even on relatively small integer strings it has advantages:
Flatten[ImportString["1 2 3 4 5 6", "Table"]]
{1,2,3,4,5,6}
Head /@ %
{Integer, Integer, Integer, Integer, Integer, Integer}
FromDigits /@ StringSplit["1 2 3 4 5 6"]
ToExpression@StringSplit["1 2 3 4 5 6"]
StringCases["1 2 3 4 5 6", ns : NumberString :> FromDigits[ns]]
ToExpression@StringCases["1 2 3 4 5 6", NumberString]
all give
(* {1, 2, 3, 4, 5, 6} *)