集册 Java实例教程 合并连接两个字符串数组

合并连接两个字符串数组

欢马劈雪     最近更新时间:2020-01-02 10:19:05

613
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
合并连接两个字符串数组
/* from 时 代 J a v a - nowjava.com*/

//package com.nowjava;


public class Main {

    public static void main(String[] argv) {

        String sep = "nowjava.com";

        String[] a1 = new String[] { "1", "abc", "level", null,

                "nowjava.com", "asdf 123" };

        String[] a2 = new String[] { "1", "abc", "level", null,

                "nowjava.com", "asdf 123" };

        System.out.println(mergeJoin(sep, a1, a2));

    }


    public static String mergeJoin(String sep, String[] a1, String[] a2) {

        if (a1.length != a2.length) {

            System.out

                    .println("Unable to merge String arrays of different length!");

            return join(a1);

        }


        StringBuilder sb = new StringBuilder(a1[0]);/*时代Java公众号 - N o w J a  v a . c o m 提供*/

        sb.append(sep).append(a2[0]);

        for (int i = 1; i < a1.length; i++)

            sb.append(" ").append(a1[i]).append(sep).append(a2[i]);

        return sb.toString();

    }


    public static String join(Object[] array) {

        return join(" ", array);

    }


    public static String join(String sep, Object[] array) {

        StringBuilder sb = new StringBuilder(array[0].toString());

        for (int i = 1; i < array.length; i++)

            sb.append(sep).append(array[i].toString());

        return sb.toString();

    }


    public static String join(String[] array) {

        return join(" ", array);

    }


    public static String join(String sep, String[] array) {

        StringBuilder sb = new StringBuilder(array[0]);

        for (int i = 1; i < array.length; i++)

            sb.append(sep).append(array[i]);

        return sb.toString();

    }


    public static String join(int[] array) {

        return join(" ", array);

    }


    public static String join(String sep, int[] array) {

        StringBuilder sb = new StringBuilder(Integer.toString(array[0]));

        for (int i = 1; i < array.length; i++)

            sb.append(sep).append(array[i]);

        return sb.toString();

    }


    
展开阅读全文