join String array to String - Java java.lang

Java examples for java.lang:String Join

Introduction

The following code shows how to join.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String separator = "java2s.com";
        String[] stringarray = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(join(separator, stringarray));
    }//  w ww  . j  a  va2 s .  com

    public static String join(String separator, String[] stringarray) {
        if (stringarray == null)
            return null;
        else
            return join(separator, stringarray, 0, stringarray.length);
    }

    public static String join(String separator, String[] stringarray,
            int startindex, int count) {
        String result = "";

        if (stringarray == null)
            return null;

        for (int index = startindex; index < stringarray.length
                && index - startindex < count; index++) {
            if (separator != null && index > startindex)
                result += separator;

            if (stringarray[index] != null)
                result += stringarray[index];
        }

        return result;
    }
}

Related Tutorials