0

Possible Duplicate:
Java StringTokenizer, empty null tokens

Considering this java snippet:

public class Test {

    public static void main(String[] args) {
        String s1 = "1;2;3;4;5";
        String s2 = "1;2;;;";

        String[] splits1 = s1.split(";");
        String[] splits2 = s2.split(";");

        System.out.println(splits1.length);
        System.out.println(splits2.length);
    }
}

OUTPUT:

5
2

I need some alternatives to extracting arrays with same lengths.

If there are four semicolons (";") in the searched string (ex s2) then I would like to have length=5 of splited array (splits2) with null elements where appropriate (splits2[2]=null, splits2[3]=null etc).

Can you please provide solutions?

4

1 回答 1

1

1.在“;”之间使用“空格” 具有相同长度的数组。您将有空格不为空

例如:

   String[] s = "1;2; ; ;" ; 

2.数组是一个可以为null的对象,如果里面包含引用变量,则可以为null但原始类型不能为null。So i am using space.

//////////////////已编辑///////////////

使用下面的代码片段,它的工作......

String a = "1;2;;;;";
        char[] chArr = a.toCharArray();

        String temp = new String();
        String[] finalArr = new String[a.length()];

        for (int i = 0; i < chArr.length; i++) {

            try {
                temp = chArr[i] + "";
                Integer.parseInt(temp);
                finalArr[i] = temp;

            } catch (NumberFormatException ex) {

                finalArr[i] = null;

            }

        }
        for (String s : finalArr){
            System.out.println(s);
        }
             System.out.println(finalArr.length);
于 2012-07-25T10:19:25.140 回答