Monday, 27 May 2019

Java: Repeat string n times


Approach 1: Using concatenation
public static String repeat(String str, int n) {
         if(str == null || n <= 1) {
                  return str;
         }
        
         StringBuilder builder = new StringBuilder();
        
         for(int i = 0; i < n; i++) {
                  builder.append(str);
         }
        
        
         return builder.toString();
}

App.java
package com.sample.app;

public class App {

 public static String repeat(String str, int n) {
  if(str == null || n <= 1) {
   return str;
  }
  
  StringBuilder builder = new StringBuilder();
  
  for(int i = 0; i < n; i++) {
   builder.append(str);
  }
  
  
  return builder.toString();
 }
 
 public static void main(String args[]) {
  String str = "Hello";
  String repeatd3Tiimes = repeat(str, 3);
  
  System.out.println("str : " + str);
  System.out.println("repeatd3Tiimes : " + repeatd3Tiimes);
 }

}

Approach 2: Using repeat method. (This is supported from java11 onwards).

Example
String str = "Hello";
String repeated = str.repeat(3);


App.java
package com.sample.app;

public class App {

 public static String repeat(String str, int n) {
  if (str == null || n <= 1) {
   return str;
  }

  StringBuilder builder = new StringBuilder();

  for (int i = 0; i < n; i++) {
   builder.append(str);
  }

  return builder.toString();
 }

 public static void main(String args[]) {
  String str = "Hello";
  String repeated = str.repeat(3);

  System.out.println(repeated);
 }

}

Approach 3: Using String.join and Collections.nCopies method
String.join("", Collections.nCopies(n, str));


App.java
package com.sample.app;

import java.util.Collections;

public class App {

 public static String repeat(String str, int n) {
  if (str == null || n <= 1) {
   return str;
  }

  return String.join("", Collections.nCopies(n, str));
 }

 public static void main(String args[]) {
  String str = "Hello";
  String repeated = repeat(str, 3);

  System.out.println(repeated);
 }

}


You may like


No comments:

Post a Comment