实现以下2个接口(必做)

不能使用语言的基本分割组合函数(如Java的String.split,php的explode和implode)

1) 字符串拆分成数组如”ab&&2”通过”&&”做分隔符,分割得到字符串数组[“ab”,”2”]

2) 实现字符串组合,如[“ab”,”2”]通过”&&”分隔符,组合成字符串”ab&&2”

作者:冒险团

链接:

https://www.nowcoder.com/interview/center?entranceType=导航栏

来源:牛客网

public class StringSplitterAndJoiner {

    public static void main(String[] args) {
        String inputString = "ab&&2";
        String delimiter = "&&";

        // 分割字符串
        String[] splitResult = splitString(inputString, delimiter);
        for (String s : splitResult) {
            System.out.println(s);
        }

        // 组合字符串
        String[] array = {"ab", "2"};
        String joinResult = joinString(array, delimiter);
        System.out.println(joinResult);
    }

    // 字符串拆分成数组
    public static String[] splitString(String str, String delimiter) {
        ArrayList<String> list = new ArrayList<>();
        int len = delimiter.length();
        int start = 0;
        int i = 0;
        while (i < str.length() - len + 1) {
            if (str.substring(i, i + len).equals(delimiter)) {
                list.add(str.substring(start, i));
                start = i + len;
                i = start;
            } else {
                i ++;
            }
        }
        list.add(str.substring(start));
        return list.toArray(new String[0]);
    }

    // 实现字符串组合
    public static String joinString(String[] array, String delimiter) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            result.append(array[i]);
            if (i < array.length - 1) {
                result.append(delimiter);
            }
        }
        return result.toString();
    }
}