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条回答
Root(大扎)
2楼-- · 2020-05-14 05:04

Try this Using the substring(int start, int end); method

String myLongString = "abcdefghij";
if (myLongString .length() >= 10)
String shortStr = myLongString.substring(0, 5)+ "...";

this will return abcde.

查看更多
The star\"
3楼-- · 2020-05-14 05:05

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!

查看更多
叼着烟拽天下
4楼-- · 2020-05-14 05:05
char[] chars = new char[10];
Arrays.fill(chars, '*');
String text = new String(chars);
查看更多
欢心
5楼-- · 2020-05-14 05:07

Try this jobber

String stringy =null;
 byte[] buffer =  new byte[100000];
            for (int i = 0; i < buffer.length; i++) {
            buffer[i] =0;

        }
            stringy =StringUtils.toAsciiString(buffer);
查看更多
Animai°情兽
6楼-- · 2020-05-14 05:11

You can use a while loop like this:

String text = "Hello";
while (text.length() < 10) { text += "*"; }
System.out.println(text);

Will give you:

Hello*****

Or get the same result with a custom method:

    public static String extendString(String text, String symbol, Integer len) {
        while (text.length() < len) { text += symbol; }
        return text;
    }

Then just call:

extendString("Hello", "*", 10)

It may also be a good idea to set a length check to prevent infinite loop.

查看更多
贼婆χ
7楼-- · 2020-05-14 05:14

No need to do the loop, and using just standard Java library classes:

protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
  if (length > 0) {
    char[] array = new char[length];
    Arrays.fill(array, charToFill);
    return new String(array);
  }
  return "";
}

As you can see, I also added suitable code for the length == 0 case.

查看更多
登录 后发表回答