JAVA中如何将空格分隔的整数字符串转换为数组 [英] how to convert an integer string separated by space into an array in JAVA

查看:81
本文介绍了JAVA中如何将空格分隔的整数字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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!

推荐答案

你忘记了

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

  • resetting temp to 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);

循环后再次

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

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

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); 
}

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

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

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

<小时>

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


Other approach could be using Scanner and 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

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();
}

这篇关于JAVA中如何将空格分隔的整数字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆