Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Create a new String instance with specified length and filled with specific character. Best solution? [duplicate]

Tags:

java

string

I did check the other questions; this question has its focus on solving this particular question the most efficient way.

Sometimes you want to create a new string with a specified length, and with a default character filling the entire string.

ie, it would be cool if you could do new String(10, '*') and create a new String from there, with a length of 10 characters all having a *.

Because such a constructor does not exist, and you cannot extend from String, you have either to create a wrapper class or a method to do this for you.

At this moment I am using this:

protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {     char[] array = new char[length];     int pos = 0;     while (pos < length) {         array[pos] = charToFill;         pos++;     }     return new String(array); } 

It still lacks any checking (ie, when length is 0 it will not work). I am constructing the array first because I believe it is faster than using string concatination or using a StringBuffer to do so.

Anyone else has a better sollution?

like image 624
Stefan Hendriks Avatar asked Nov 26 '09 10:11

Stefan Hendriks


People also ask

How do you declare a string of a specific size in Java?

To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets. String arrayName[] = new String[size]; //or String[] arrayName = new String[size];

How do you duplicate a string in Java?

To make a copy of a string, we can use the built-in new String() constructor in Java. Similarly, we can also copy it by assigning a string to the new variable, because strings are immutable objects in Java.

How do I create a string of the same character?

char Array With a for Loop. We can fill a fixed size char array with our desired character and convert that to a string: char[] charArray = new char[N]; for (int i = 0; i < N; i++) { charArray[i] = 'a'; } String newString = new String(charArray); assertEquals(EXPECTED_STRING, newString);

How do you add a special character to a string in Java?

To display them, Java has created a special code that can be put into a string: \". Whenever this code is encountered in a string, it is replaced with a double quotation mark.


2 Answers

Apache Commons Lang (probably useful enough to be on the classpath of any non-trivial project) has StringUtils.repeat():

String filled = StringUtils.repeat("*", 10); 

Easy!

like image 107
Cowan Avatar answered Sep 20 '22 04:09

Cowan


Simply use the StringUtils class from apache commons lang project. You have a leftPad method:

StringUtils.leftPad("foobar", 10, '*'); // Returns "****foobar" 
like image 27
Romain Linsolas Avatar answered Sep 21 '22 04:09

Romain Linsolas