Converting string into array of ints ex String st = “1 2 3 4 5” into ar=[1,2,3,4,5]

只愿长相守 提交于 2021-02-04 21:39:54

问题


I am reading in a string, as an entire line of numbers, separated by spaces, ie ie 1 2 3 4 5. I want to convert them into an array of integers, so that I can manipulate them. But this code doesn't work. It says incompatible types.

String str = br.readLine();
int[] array = new int[4];
StringTokenizer tok = new StringTokenizer(str," ", true);
boolean expectDelim = false;
int i = 0;

while (tok.hasMoreTokens()) {
    String token = tok.nextToken();
    ar[i] = Integer.parseInt(token);
    i++;
}

回答1:


If you have a String s = "1 2 3 4 5" then you can split it into separate bits like this:

String[] bits = s.split(" ");

Now you have to put them into an int[] by converting each one:

int[] nums = new int[bits.length];
int i=0;
for (String s: bits)
    nums[i++] = Integer.parseInt(s);

This will loop through each of the small strings in the split array, convert it to an integer, and put it into the new array.




回答2:


You don't need the delimiters. Change this:

StringTokenizer tok = new StringTokenizer(str," ", true);

to this:

StringTokenizer tok = new StringTokenizer(str," ");

What's happening in your code is that it's trying to parse (space) as an int.

Alternatively, nowadays most people would just use String.split(...), as pointed out by chiastic-security.




回答3:


You can use the following code to convert a String consisting of whitespace-separated numbers to an int[]:

import static java.util.Arrays.stream;

public class ConvertString {
    public static void main(final String... args) {
        final String s = "1 2 3 4 5";
        final int[] numbers = stream(s.split("\\s+")).mapToInt(Integer::parseInt).toArray();

        // Print it as a demo.
        for (final int number : numbers)
            System.out.format("%s ", number);
        System.out.println();
    }
}



回答4:


Java 8 style solution:

String input = "1 2 3 4 5";

int[] numbers = Arrays.stream(input.split("\\s+"))
        .mapToInt(Integer::parseInt).toArray();


来源:https://stackoverflow.com/questions/27360633/converting-string-into-array-of-ints-ex-string-st-1-2-3-4-5-into-ar-1-2-3-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!