如何从字符串到子字符串获取数字并保留在数组中?

时间:2017-06-21 14:40:33

标签: java

我在字符串中有数字。我想通过循环或任何方式剪切并保持数组 然后再将这个数组循环到最低到最高等级。 如何获得与我构建的这些数组相同的结果。 谢谢。

public class Main
{
    static String input = "1,3,7,11,5,16,13,12,22,14";
    public static void main(String[] args)
    {
       /*
        int[] keep = new int[11]; //How I can know if I don't know total index in first time.`enter code here`
        keep[0] = 1;
        keep[1] = 3;
        keep[2] = 7;
        keep[3] = 11;
        keep[4] = 5;
        keep[5] = 16;
        keep[6] = 13;
        keep[7] = 12;
        keep[8] = 22;
        keep[9] = 14;

        int[] rank = new int[keep.length];
        rank[0] = 1;
        rank[1] = 3;
        rank[2] = 5;
        rank[3] = 7;
        rank[4] = 11;
        rank[5] = 12;
        rank[6] = 13;
        rank[7] = 14;
        rank[8] = 16;
        rank[9] = 22;
        */

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

    }

}

3 个答案:

答案 0 :(得分:1)

您需要在输入字符串上使用split方法,然后从String转换为integer

String[] splitted=input.split(",");

int[] keep = new int[splitted.length];

for(int i=0;i<splitted.length;i++){
    keep[i]= Integer.parseInt(splitted[i]);
}

答案 1 :(得分:1)

你可以:

  • 将字符串拆分为冒号
  • 流生成的数组
  • 将其映射到整数解析数组中的每个元素
  • 将结果转换为数组
基本上是这样的:

String input = "1,3,7,11,5,16,13,12,22,14";
int[] foo = Stream.of(input.split(",")).mapToInt(Integer::parseInt).toArray();

System.out.println(Arrays.toString(foo));

答案 2 :(得分:1)

你可以这样做。

having