Java how to return split array to function?

I am learning Java, and as a simple exercise, I am trying to create custom serialization and deaserization functions. However, I am having trouble returning a split array. I expect the function to return 4 elements of the array ... bob, roger, tim and the last one is empty because it breaks with "|", but it returns all characters separately, for example:

b
o
b
|
r
...

      

I'm sure there is something small that I forgot ... 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);
        }
    }
}

      

+3


source to share


1 answer


The character is |

interpreted differently by the regex engine, which uses split

mostly "empty string or empty string". Since you have a constant instead of a literal one passed to split

, I have to run it through Pattern.quote

before going to split

, so this is interpreted literally.

This method creates a string that can be used to create a pattern that matches the string s as if it were a literal pattern.

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

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

      



And when using:

return str.split(SPLIT_REGEX);

      

+4


source







All Articles