Daniel Valland
Daniel Valland

Reputation: 1107

Java how to return a split array in a function?

I am learning Java, and as a simple exercise, I am trying to make custom array serialize and de-serialize functions. However, I am having some problems returning a split array. I am expecting the function to return 4 array elements... bob,roger,tim and the last one empty because it splits by "|", but it returns all the characters separate, like:

b
o
b
|
r
...

I am sure that there is something small that I have overlooked... Here is my code:

public class test{

    public static String SPLIT_CHAR = "|";

    // public functions::
    public static String SERIALIZE(String[] arr){ 
        String RES="";
        for (String item : arr){
            RES +=item+SPLIT_CHAR;
        }
        return RES;
    }

    public static String[] DE_SERIALIZE(String str){
        return str.split(SPLIT_CHAR);
    }

    public static void main (String[] args){
        String[] TestArr = {"bob","roger","tim"};
        System.out.println(SERIALIZE(TestArr));
        String[] DES_TEST = DE_SERIALIZE(SERIALIZE(TestArr));
        for (String Item : DES_TEST){
            System.out.println(Item);
        }
    }
}

Upvotes: 3

Views: 265

Answers (1)

rgettman
rgettman

Reputation: 178263

The | character is interpreted differently by the regular expression engine that split uses, basically "empty string or empty string". Because you have a constant instead of a literal being passed to split, I would run it through Pattern.quote before passing to split, so that it's interpreted literally.

This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.

Metacharacters or escape sequences in the input sequence will be given no special meaning.

public static String SPLIT_CHAR = "|";
public static String SPLIT_REGEX = Pattern.quote(SPLIT_CHAR);

And when using it:

return str.split(SPLIT_REGEX);

Upvotes: 4

Related Questions