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?

Community
  • 1
  • 1
George D
  • 2,327
  • 3
  • 20
  • 26

1 Answers1

1

1. Use "space" between the ";" to have the arrays of same length. You will have Empty spaces not null

Eg:

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

2. Array is an object which can be null, and if it contains the reference variable inside it, those can be null, but primitive types cannot be null.So i am using space.

/////////////////////EDITED/////////////////

Use this below snippet, ITS WORKING....

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);
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • I shouldn't modify the searched string to have spaces between semicolons – George D Jul 25 '12 at 11:02
  • I guess @dadu 's problem is that he can't choose the input data so trying to split the data as it is should be the solution given. – cosmincalistru Jul 25 '12 at 11:05
  • @dadu...check out my edited part.... it contains the code you want.. – Kumar Vivek Mitra Jul 25 '12 at 11:29
  • @KumarVivekMitra : Thanks for your ideea, it's an interesting approach. It seems that a less complicated solution is using the second parameter of split. Can you edit your answer and include as an other alternative solution: String[] splits2 = s2.split(";", -1); ? – George D Jul 25 '12 at 13:52