Return input repeated multiplier times, with separator in between. - Java java.lang

Java examples for java.lang:String Repeat

Description

Return input repeated multiplier times, with separator in between.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String input = "java2s.com";
        int multiplier = 42;
        String separator = "java2s.com";
        System.out/*from   w  w w .  j  av  a2 s . co m*/
                .println(repeatWithSeparator(input, multiplier, separator));
    }

    /**
     * Return input repeated multiplier times, with separator in between.
     * multiplier has to be greater than or equal to 0. If the multiplier is
     * <= 0, the function will return an empty string.
     *
     * @param input
     * the string to multiply
     * @param multiplier
     * how many times to repeat it
     * @param separator
     * a separator String to be inserted between repetitions
     * @return the resulting String
     */
    public static String repeatWithSeparator(final String input,
            final int multiplier, final String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < multiplier; i++) {
            if (i > 0) {
                sb.append(separator);
            }
            sb.append(input);
        }
        return sb.toString();
    }
}

Related Tutorials