repeat()
is a StringUtils
class that is used to repeat a given string/character a number of times to form a new string. The method also takes a string separator that is injected each time.
StringUtils
The definition of StringUtils
can be found in the Apache Commons Lang
package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the StringUtils
class as follows.
import org.apache.commons.lang3.StringUtils;
public static String repeat(final String str, final String separator, final int repeat)
final String str
: The string to repeat.
final String separator
: The string separator to inject.
final int repeat
: The number of times to repeat.
This method returns a new string with the given string repeated repeat
number of times.
public static String repeat(final String str, final int repeat)
public static String repeat(final char ch, final int repeat)
string = "educative"
repeat = 3
separator = "-"
The method returns educative-educative-educative
, where the string is repeated three times with the string separator injected after every repetition.
string = "educative"
repeat = 2
The method returns educativeeducative
, where the string is repeated two times.
string = null
repeat = 3
The method returns null
, as the input string is null
.
string = "educative"
repeat = -1
The method returns `` as the number of times to repeat is -1
, therefore it will be treated as zero.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {// Example 1String s = "educative";int repeat = 3;String separator = "-";System.out.printf("The output of StringUtils.repeat() for the string - '%s' is '%s'", s, StringUtils.repeat(s, separator, repeat));System.out.println();// Example 2s = "educative";repeat = 2;System.out.printf("The output of StringUtils.repeat() for the string - '%s' is '%s'", s, StringUtils.repeat(s, repeat));System.out.println();// Example 3s = null;repeat = 2;System.out.printf("The output of StringUtils.repeat() for the string - '%s' is '%s'", s, StringUtils.repeat(s, repeat));System.out.println();// Example 4s = "educative";repeat = -1;System.out.printf("The output of StringUtils.repeat() for the string - '%s' is '%s'", s, StringUtils.repeat(s, repeat));System.out.println();}}
The output of the code will be as follows.
The output of StringUtils.repeat() for the string - 'educative' is 'educative-educative-educative'
The output of StringUtils.repeat() for the string - 'educative' is 'educativeeducative'
The output of StringUtils.repeat() for the string - 'null' is 'null'
The output of StringUtils.repeat() for the string - 'educative' is ''
Free Resources