如何将空格分隔的整数字符串转换为JAVA中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29219418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:35:43  来源:igfitidea点击:

how to convert an integer string separated by space into an array in JAVA

javaarraysstring

提问by Learn and practice

Suppose I have a string "1 23 40 187 298". This string only contains integers and spaces. How can I convert this string to an integer array, which is [1,23,40,187,298]. this is how I tried

假设我有一个字符串“1 23 40 187 298”。此字符串仅包含整数和空格。如何将此字符串转换为整数数组,即 [1,23,40,187,298]。这就是我尝试的方式

public static void main(String[] args) {
    String numbers = "12 1 890 65";
    String temp = new String();
    int[] ary = new int[4];
    int j=0;
    for (int i=0;i<numbers.length();i++)
    {

        if (numbers.charAt(i)!=' ')
            temp+=numbers.charAt(i);
        if (numbers.charAt(i)==' '){
            ary[j]=Integer.parseInt(temp);
            j++;
        }
    }
}

but it doesn't work, please offer some help. Thank you!

但它不起作用,请提供一些帮助。谢谢!

采纳答案by Pshemo

You are forgetting about

你忘记了

  • resetting tempto empty string after you parse it to create place for new digits
  • that at the end of your string will be no space, so

    if (numbers.charAt(i) == ' ') {
        ary[j] = Integer.parseInt(temp);
        j++;
    }
    

    will not be invoked, which means you need invoke

    ary[j] = Integer.parseInt(temp);
    

    once again after your loop

  • temp在解析它以创建新数字的位置后重置为空字符串
  • 在你的字符串末尾将没有空格,所以

    if (numbers.charAt(i) == ' ') {
        ary[j] = Integer.parseInt(temp);
        j++;
    }
    

    不会被调用,这意味着你需要调用

    ary[j] = Integer.parseInt(temp);
    

    循环后再次



But simpler way would be just using split(" ")to create temporary array of tokens and then parse each token to intlike

但更简单的方法是使用split(" ")创建临时令牌数组,然后解析每个令牌以int喜欢

String numbers = "12 1 890 65";
String[] tokens = numbers.split(" ");
int[] ary = new int[tokens.length];

int i = 0;
for (String token : tokens){
    ary[i++] = Integer.parseInt(token); 
}

which can also be shortened with streams added in Java 8:

也可以通过在Java 8 中添加的流来缩短:

String numbers = "12 1 890 65";
int[] array = Stream.of(numbers.split(" "))
                    .mapToInt(token -> Integer.parseInt(token))
                    .toArray();


Other approach could be using Scannerand its nextInt()method to return all integers from your input. With assumption that you already know the size of needed array you can simply use

可以使用其他方法Scanner及其nextInt()方法从您的输入返回所有整数。假设您已经知道所需数组的大小,您可以简单地使用

String numbers = "12 1 890 65";
int[] ary = new int[4];

int i = 0;
Scanner sc = new Scanner(numbers);
while(sc.hasNextInt()){
    ary[i++] = sc.nextInt();
}

回答by esin88

For java 8+ you can use this way:

对于 java 8+,您可以使用这种方式:

final Integer[] ints = Arrays.stream(numbers.split(" "))
        .map(Integer::parseInt)
        .toArray(Integer[]::new);

or, if you need primitive ints, you can use this:

或者,如果你需要原始整数,你可以使用这个:

final int[] ints = Arrays.stream(numbers.split(" "))
        .mapToInt(Integer::parseInt)
        .toArray();

回答by copeg

Reset the tmp String to "" after you parse the integer unless you wish to continue to append all the numbers of the String together. There are also alternatives as well - for instance splitting the String into an array on the space characeter, and then parsing the numbers individually

解析整数后将 tmp 字符串重置为 "",除非您希望继续将字符串的所有数字附加在一起。还有其他选择 - 例如将字符串拆分为空格字符上的数组,然后单独解析数字

回答by Jobin Thomas

Try this out,

试试这个,

public static void main(String[] args) {
    String numbers = "12 1 890 65";
    String[] parts = numbers.split(" ");

    int[] ary = new int[4];
    int element1 = Integer.parseInt(parts[0]);
    int element2 = Integer.parseInt(parts[1]);
    int element3 = Integer.parseInt(parts[2]);
    int element4 = Integer.parseInt(parts[3]);

    ary[0] = element1;
    ary[1] = element2;
    ary[2] = element3;
    ary[3] = element4;

    for(int i=0; i<4; i++){
        System.out.println(ary[i]);
    }

}

回答by anne rabbit

I met similar question in android development. I want to convert a long string into two array -String array xtokens and int array ytokens.

我在android开发中遇到过类似的问题。我想将一个长字符串转换为两个数组 -String 数组 xtokens 和 int 数组 ytokens。

String result = "201 5 202 8 203 53 204 8";             
String[] tokens = result.split(" ");
String[] xtokens = new String[tokens.length/2 + 1];
int[] ytokens = new int[tokens.length/2 + 1];

for(int i = 0, xplace = 0, yplace = 0; i<tokens.length; i++){
    String temptoken = new String(tokens[i]);
    if(i % 2 == 0){
        xtokens[xplace++] = temptoken;
    }else {
        ytokens[yplace++] = Integer.parseInt(temptoken);
    }
}

You can first convert this string into an string array separated by space, then convert it to int array.

可以先把这个字符串转换成空格分隔的字符串数组,再转换成int数组。