Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Generating strings of length x

Tags:

java

string

I have some 'heavy' string manipulation in my Java program, which often involves iterating through a String and replacing certain segments with filler characters, usually "@". These are characters are later removed but are used so that the length of the String and the current index are kept intact during the iteration.

This process usually involves replacing more than 1 character at a time.
e.g.
I might need to replace "cat" with "@@@" in the string "I love cats", giving "I love @@@s", So often I need to create strings of "@" with x length.

In python, this is easy.

NewString = "@" *x

In Java, I find my current method revolting.

String NewString = "";
for (int i=0; i< x; i++)  {  
    NewString = NewString.concat("@");  }

Is there a proper, pre-established method for doing this?
Does anybody have a shorter, more 'golfed' method?
Thanks!


Specs:
Java SE (Jre7)
Windows 7 (32)

like image 785
Anti Earth Avatar asked Mar 18 '26 21:03

Anti Earth


2 Answers

It's not clear to me what kind of regex the comments are suggesting, but creating a string filled with a particular character to the given length is pretty easy:

public static String createString(char character, int length) {
    char[] chars = new char[length];
    Arrays.fill(chars, character);
    return new String(chars);
}
like image 134
Jon Skeet Avatar answered Mar 21 '26 10:03

Jon Skeet


Guava has a nice little method Strings.repeat(String, int). Looking at the source of that method, it basically amounts to this:

StringBuilder builder = new StringBuilder(string.length() * count);
for (int i = 0; i < count; i++) {
  builder.append(string);
}
return builder.toString();
like image 27
Paul Bellora Avatar answered Mar 21 '26 11:03

Paul Bellora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!