Java - Create a new String instance with specified

2020-05-14 04:23发布

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?

标签: java string
17条回答
Bombasti
2楼-- · 2020-05-14 04:56

One extra note: it seems that all public ways of creating a new String instance involves necessarily the copy of whatever buffer you are working with, be it a char[], a StringBuffer or a StringBuilder. From the String javadoc (and is repeated in the respective toString methods from the other classes):

The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

So you'll end up having a possibly big memory copy operation after the "fast filling" of the array. The only solution that may avoid this issue is the one from @mlk, if you can manage working directly with the proposed CharSequence implementation (what may be the case).

PS: I would post this as a comment but I don't have enough reputation to do that yet.

查看更多
不美不萌又怎样
3楼-- · 2020-05-14 04:58
public static String fillString(int count,char c) {
    StringBuilder sb = new StringBuilder( count );
    for( int i=0; i<count; i++ ) {
        sb.append( c ); 
    }
    return sb.toString();
}

What is wrong?

查看更多
三岁会撩人
4楼-- · 2020-05-14 05:03

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

StringUtils.leftPad("foobar", 10, '*'); // Returns "****foobar"
查看更多
做自己的国王
5楼-- · 2020-05-14 05:03

In Java 11, you have repeat:

String s = " ";
s = s.repeat(1);

(Although at the time of writing still subject to change)

查看更多
啃猪蹄的小仙女
6楼-- · 2020-05-14 05:03

Solution using Google Guava, since I prefer it to Apache Commons-Lang:

/**
 * Returns a String with exactly the given length composed entirely of
 * the given character.
 * @param length the length of the returned string
 * @param c the character to fill the String with
 */
public static String stringOfLength(final int length, final char c)
{
    return Strings.padEnd("", length, c);
}
查看更多
倾城 Initia
7楼-- · 2020-05-14 05:04

Some possible solutions.

This creates a String with length-times '0' filled and replaces then the '0' with the charToFill (old school).

String s = String.format("%0" + length + "d", 0).replace('0', charToFill);

This creates a List containing length-times Strings with charToFill and then joining the List into a String.

String s = String.join("", Collections.nCopies(length, String.valueOf(charToFill)));

This creates a unlimited java8 Stream with Strings with charToFill, limits the output to length and collects the results with a String joiner (new school).

String s = Stream.generate(() -> String.valueOf(charToFill)).limit(length).collect(Collectors.joining());
查看更多
登录 后发表回答