拆分字符串,不带逗号

时间:2013-11-08 09:52:03

标签: android arrays random

我有一个生成9个随机数的方法,至少我将它们存储在一个String上以显示在控制台上。这是功能:

public static String GenerateNumbers(){
    int[] NumberList = new int[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String[] ar = Arrays.toString(NumberList).split("[\\[\\]]")[1].split(", ");
    String a = Arrays.toString(ar);
    return a;
}

当我在控制台上看到这个字符串时,就像:[20, 28, 33, 46, 46, 57, 81, 83, 90]

我需要看到的是:[20 28 33 46 46 57 81 83 90]

如果:20 28 33 46 46 57 81 83 90

那将是完美的

5 个答案:

答案 0 :(得分:1)

使用TextUtils.join()加入一个CharSequence的数组(也可以是String)。

public static String GenerateNumbers(){
    Integer[] NumberList = new Integer[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String a = TextUtils.join(" ",NumberList);
    return a;
}

答案 1 :(得分:1)

这可能对您有所帮助

public static void main(String[] args) {
    String a = "[20, 28, 33, 46, 46, 57, 81, 83, 90]";
    String b = a.substring(a.indexOf("[")+1, a.indexOf("]"));
    StringTokenizer token = new StringTokenizer(b, ",");
    while(token.hasMoreElements()){
        System.out.print(token.nextElement());
    }
}


//output
20 28 33 46 46 57 81 83 90

答案 2 :(得分:1)

使用此,

public static String GenerateNumbers(){
    int[] NumberList = new int[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String a="";
    for(int i=0;i<9;i++){
        a+= NumberList[i]+" ";
    }
    a = a.trim();
    return a;
}

答案 3 :(得分:1)

像这样改变你的方法..

public static String GenerateNumbers() {
    int[] NumberList = new int[9];
    for (int i = 0; i < 9; i++) {
        NumberList[i] = (int) Math.floor(Math.random() * (100 - 10 + 1)
                + 10);
    }
    Arrays.sort(NumberList);
    String a = Arrays.toString(NumberList);
    a = a.replaceAll(",", "");
    a = a.replaceAll("[\\[\\]]", "");
    return a;
}

输出:

16 28 30 37 45 70 73 85 92

答案 4 :(得分:1)

在返回字符串之前添加一行代码,您将获得完美的输出:

public static String GenerateNumbers(){
    int[] NumberList = new int[9];

    for (int i = 0; i < 9; i++){
        NumberList[i] = (int) Math.floor(Math.random()*(100-10+1)+10);
    }
    Arrays.sort(NumberList);
    String[] ar = Arrays.toString(NumberList).split("[\\[\\]]")[1].split(", ");
    String a = Arrays.toString(ar);

    //add this line to remove characters you don't need
    a = a.replace("[", "").replace(",", "").replace("]", "");

    return a;
}