Java - 创建一个具有指定长度并填充特定字符的新 String 实例。最佳解决方案?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1802915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:49:03  来源:igfitidea点击:

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

javastring

提问by Stefan Hendriks

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 *.

即,如果您可以new String(10, '*')从那里创建一个新的字符串,长度为 10 个字符的所有字符串都带有 * ,那就太酷了。

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.

因为这样的构造函数不存在,并且您不能从 String 扩展,所以您必须创建一个包装类或一个方法来为您执行此操作。

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.

它仍然缺乏任何检查(即,当长度为 0 时,它将不起作用)。我首先构造数组,因为我相信它比使用字符串连接或使用 StringBuffer 这样做更快。

Anyone else has a better sollution?

其他人有更好的解决方案吗?

采纳答案by Cowan

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

Apache Commons Lang(可能足够有用以用于任何非平凡项目的类路径)具有StringUtils.repeat()

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

Easy!

简单!

回答by Romain Linsolas

Simply use the StringUtils class from apache commons langproject. You have a leftPadmethod:

只需使用apache commons lang项目中的 StringUtils 类。你有一个leftPad方法:

StringUtils.leftPad("foobar", 10, '*'); // Returns "****foobar"

回答by unwind

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

无需执行循环,只需使用标准 Java 库类:

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 == 0case.

如您所见,我还为length == 0案例添加了合适的代码。

回答by Alexander Pavloshchuk

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?

怎么了?

回答by Karl

To improve performance you could have a single predefined sting if you know the max length like:

为了提高性能,如果你知道最大长度,你可以有一个预定义的刺痛:

String template = "####################################";

字符串模板 = "##################################";

And then simply perform a substring once you know the length.

然后在知道长度后简单地执行一个子字符串。

回答by Michael Lloyd Lee mlk

The above is fine. Do you mind if I ask you a question - Is this causing you a problem? It seams to me you are optimizing before you know if you need to.

以上没问题。你介意我问你一个问题 - 这是否给你带来了问题?在我看来,您在知道是否需要之前正在优化。

Now for my over engineered solution. In many (thou not all) cases you can use CharSequence instead of a String.

现在是我过度设计的解决方案。在许多(不是全部)情况下,您可以使用 CharSequence 而不是 String。

public class OneCharSequence implements CharSequence {
  private final char value;
  private final int length;
  public OneCharSequence(final char value, final int length) {
    this.value = value;
    this.length = length;
  }
  public char   charAt(int index)  {
     if(index < length) return value;
     throw new IndexOutOfBoundsException();
  }
  public int length() {
    return length;
  }
  public CharSequence subSequence(int start, int end) {
     return new OneCharSequence(value, (end-start));
  }
  public String toString() {
    char[] array = new char[length];
    Arrays.fill(array, value);
    return new String(array);
  }
}

回答by Chuim

One extra note: it seems that all public ways of creating a new Stringinstance involves necessarily the copy of whatever buffer you are working with, be it a char[], a StringBufferor a StringBuilder. From the Stringjavadoc (and is repeated in the respective toStringmethods from the other classes):

一个额外的注意事项:似乎所有创建新String实例的公共方法都必须涉及您正在使用的任何缓冲区的副本,无论是 a char[]、 aStringBuffer还是 a StringBuilder。来自Stringjavadoc(并toString在其他类的相应方法中重复):

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 CharSequenceimplementation (what may be the case).

因此,在“快速填充”数组之后,您最终可能会进行大内存复制操作。唯一可以避免此问题的解决方案是来自 @mlk 的解决方案,前提是您可以直接使用建议的CharSequence实现进行管理(可能是这种情况)。

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

PS:我会将此作为评论发布,但我还没有足够的声誉来做到这一点。

回答by dfa

using Dollaris simple:

使用Dollar很简单:

String filled = $("=").repeat(10).toString(); // produces "=========="

回答by Qadir Hussain

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

试试这个 使用 substring(int start, int end); 方法

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

this will return abcde.

这将返回 abcde。

回答by Pavel Netesa

char[] chars = new char[10];
Arrays.fill(chars, '*');
String text = new String(chars);