13

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!

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
SuTron
  • 1,708
  • 1
  • 11
  • 21

7 Answers7

16

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

ciao
  • 25,774
  • 2
  • 58
  • 139
12
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} *)
kglr
  • 394,356
  • 18
  • 477
  • 896
  • 3
    First is close to fastest possible using native MMA, better than twice as fast as accepted, and no upvotes? Fixed: +1 – ciao Apr 04 '15 at 05:17
11
Flatten[ImportString["1 2 3 4 5 6", "Table"]]

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

Head /@ %

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

Andrew
  • 10,569
  • 5
  • 51
  • 104
9
res = ToExpression @ StringSplit["1 2 3 4 5 6", " "]

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

 Head /@ res

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

Revision 1

If the substrings are separated by whitespace, one can omit the 2nd argument:

ToExpression @ StringSplit["1 2 3 4 5 6"]

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

eldo
  • 67,911
  • 5
  • 60
  • 168
5

enter image description here

str = "1 2 3 4 5 6"
Interpreter[DelimitedSequence["Integer"]][str]

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

Syed
  • 52,495
  • 4
  • 30
  • 85
4
ToExpression["{" <> StringReplace["1 2 3 4 5 6", " " -> ","] <> "}"]
vapor
  • 7,911
  • 2
  • 22
  • 55
2

Using ReplaceAll and DeleteCases:

str /. x_ :> DeleteCases[ToExpression@Characters[x], Null]

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

Another way, using StringCases and DigitCharacter:

StringCases[str, ns : DigitCharacter :> FromDigits[ns]] // RepeatedTiming

({9.5965810^-6, {1, 2, 3, 4, 5, 6}}*)

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44