Java - Write code to split string to Array using String split() method

Requirements

Write code to split string to Array

Use a | as the separator.

Hint

Use String.split() as the method,

Escape | when using in split() method

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        System.out.println(java.util.Arrays.toString(string2Array(string)));
    }/*www .  j a v  a 2 s.c  o  m*/

    private final static String SPLIT_SYMBOL = "|";
    private final static String SPLIT_REGEX_SYMBOL = "\\|";

    public static String[] string2Array(String string) {
        if (string != null && !string.isEmpty()) {
     
            if (string.startsWith(SPLIT_SYMBOL)) {
                string = string.substring(1);
            }
            if (string.endsWith(SPLIT_SYMBOL)) {
                string = string.substring(0, string.length() - 1);
            }
        }
        if (string == null || string.isEmpty())
            return null;

        return string.split(SPLIT_REGEX_SYMBOL);
    }
}

Related Exercise