Concatenate a string array with spaces. - Java java.lang

Java examples for java.lang:String Array

Description

Concatenate a string array with spaces.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] args = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        int startIdx = 2;
        System.out.println(ConcatArgs(args, startIdx));
    }//from  w w w .j  a  va2s.  c o m

    /** 
     * Concatenate a string array with spaces.
     * For example if 2 strings "hello" and "world" passed in, result is "hello world".
     * 
     * @param args Array of Strings
     * @param startIdx Starting Index
     * @return Concatenated list with spaces
     */
    public static String ConcatArgs(String[] args, int startIdx) {
        StringBuilder sb = new StringBuilder();
        for (int i = startIdx; i < args.length; i++) {
            if (sb.length() > 0) {
                sb.append(" ");
            }
            sb.append(args[i]);
        }
        return sb.toString();
    }
}

Related Tutorials