How to replace plus sign by comma

Another way:

expr = a1 + a10 + a11 + a13 + a2 + a27 + a28;

ToExpression@StringDrop[ToString[#], 1] & /@ List @@ expr

(* ==> {1, 10, 11, 13, 2, 27, 28} *)

You can then Sort them.


Another option:

Block[
    {Plus = Function[Sort@ToExpression@StringReplace[ToString[{##}], LetterCharacter -> ""]]},
    a1 + a10 + a11 + a13 + a2 + a27 + a28
]
(* {1, 2, 10, 11, 13, 27, 28} *)

Works with other possibilities, such as "b123", "abc123", etc.


expr = a1 + a10 + a11 + a13 + a2 + a27 + a28

Then:

expr /. Plus -> List // ToString /@ # & // StringReplace[#, "a" -> ""] & // ToExpression // Sort

Gives:

{1, 2, 10, 11, 13, 27, 28}

Tags:

Replacement