开发者

String to array of integers

If i have a large string of numbers, is there a way to convert that into an int array? id rather not have to manually code every entry to the array...

small scale example:

String s ="12345";
int[] ints = new int[500];

how can i end up with:

int开发者_JAVA百科s[0] = 1;
ints[1] = 2;
ints[2] = 3;
ints[3] = 4;
ints[4] = 5;

without manually doing that?


for (int i = 0; i < s.length(); i++) {
    ints[i] = Character.getNumericValue(s.charAt(i));
}


for (int i=0;i<s.length();i++) {
      ints[i] = Integer.parseInt(""+s.charAt(i));
   }


You can do the following

String s ="12345";
int[] ints = new int[s.length];
for(int i=0;i<s.length;i++)
    ints[i] = s.charAt(i) - '0';

This is much faster than building a StringBuilder/String and parsing it.

Another approach is to use a wrapper instead of creating an array at all

public class Ints {
    private final String text;
    public Ints(String text) { this.text = text; }
    public int length() { return text.length(); }
    public int value(int index) { return text.charAt(index) - '0'; }
}

Ints ints = new Ints("12345");


Here an other alternative:

for (int i = 0; i < s.length(); i++) {
    ints[i] = s.charAt(i) - '0';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜