Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to repeat a string

Tags:

java

string

I'm looking for a simple commons method or operator that allows me to repeat some string n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.

String str = "abc"; String repeated = str.repeat(3);  repeated.equals("abcabcabc"); 

Related to:

repeat string javascript Create NSString by repeating another string a given number of times

Edited

I try to avoid for loops when they are not completely necessary because:

  1. They add to the number of lines of code even if they are tucked away in another function.

  2. Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".

  3. Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".

  4. They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.

  5. For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.

  6. For loops increase the number of places a bug hunter has to look.

like image 645
Ethan Heilman Avatar asked Aug 05 '09 19:08

Ethan Heilman


People also ask

How do you repeat a string?

JavaScript String repeat()The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

How do you make a string repeating characters?

Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);

How does string repeat work?

The repeat() method returns a string that has been repeated a desired number of times. If the count parameter is not provided or is a value of 0, the repeat() method will return an empty string. If the count parameter is a negative value, the repeat() method will return RangeError.

How do you repeat a string in Python?

In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.


1 Answers

Here is the shortest version (Java 1.5+ required):

repeated = new String(new char[n]).replace("\0", s); 

Where n is the number of times you want to repeat the string and s is the string to repeat.

No imports or libraries needed.

like image 120
user102008 Avatar answered Sep 19 '22 15:09

user102008