8
$\begingroup$

Saying we have a string:

"1 2 3 4 5 6"

I want to convert this to integer list. First I do:

In[82]:= str = StringReplace["1 2 3 4 5 6", " " -> ","] // List
Out[82]= {"1,2,3,4,5,6"}

No I need to convert Out[82] to be just {1,2,3,4,5,6}.

Any idea? Thanks!

$\endgroup$
3
$\begingroup$
res = ToExpression@StringSplit["1 2 3 4 5 6", " "]

{1, 2, 3, 4, 5, 6}

 Head /@ res

{Integer, Integer, Integer, Integer, Integer, Integer}

$\endgroup$
9
$\begingroup$

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: enter image description here

Even on relatively small integer strings it has advantages:

enter image description here

$\endgroup$
  • $\begingroup$ Great method! I miss your contributions. $\endgroup$ – Mr.Wizard Oct 30 '18 at 3:43
  • $\begingroup$ @Mr.Wizard - That means much coming from you! I'm still here, just been quite busy in semi-retirement herding some startups... $\endgroup$ – ciao Oct 30 '18 at 4:58
7
$\begingroup$
Flatten[ImportString["1 2 3 4 5 6", "Table"]]

{1,2,3,4,5,6}

Head /@ %

{Integer, Integer, Integer, Integer, Integer, Integer}

$\endgroup$
7
$\begingroup$
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} *)
$\endgroup$
  • 3
    $\begingroup$ First is close to fastest possible using native MMA, better than twice as fast as accepted, and no upvotes? Fixed: +1 $\endgroup$ – ciao Apr 4 '15 at 5:17
1
$\begingroup$
ToExpression["{" <> StringReplace["1 2 3 4 5 6", " " -> ","] <> "}"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.