your programing

Java-지정된 길이와 특정 문자로 채워진 새 문자열 인스턴스를 만듭니다.

lovepro 2020. 10. 8. 08:27
반응형

Java-지정된 길이와 특정 문자로 채워진 새 문자열 인스턴스를 만듭니다. 최고의 솔루션?


이 질문에 이미 답변이 있습니다.

다른 질문을 확인했습니다. 이 질문은이 특정 질문을 가장 효율적인 방법으로 해결하는 데 중점을 둡니다.

때로는 지정된 길이로 전체 문자열을 채우는 기본 문자로 새 문자열을 작성하려고합니다.

즉, new String(10, '*')10 자 길이로 모두 *가있는 새 문자열을 만들 수 있다면 멋질 것 입니다.

그러한 생성자가 존재하지 않고 String에서 확장 할 수 없기 때문에 래퍼 클래스 나이를 수행하는 메서드를 만들어야합니다.

이 순간 나는 이것을 사용하고 있습니다.

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);
}

여전히 검사가 부족합니다 (즉, 길이가 0이면 작동하지 않습니다). 문자열 연결을 사용하거나 StringBuffer를 사용하는 것보다 빠르다고 생각하기 때문에 먼저 배열을 구성하고 있습니다.

다른 사람이 더 나은 해결책을 가지고 있습니까?


Apache Commons Lang (아마 사소하지 않은 프로젝트의 클래스 경로에있을만큼 유용 할 수 있음)에는 StringUtils.repeat ()가 있습니다 .

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

쉬운!


Apache commons lang 프로젝트 의 StringUtils 클래스를 사용하기 만하면됩니다 . 당신은이 leftPad의 방법 :

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

루프를 수행 할 필요가 없으며 표준 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 "";
}

보시다시피 length == 0케이스 에 적합한 코드도 추가했습니다 .


몇 가지 가능한 해결책.

이렇게하면 길이 시간 '0'이 채워진 문자열이 생성되고 '0'이 charToFill (오래된 학교)로 바뀝니다.

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

이것은 charToFill을 사용하여 길이 시간 문자열을 포함하는 목록을 생성 한 다음 목록을 문자열에 결합합니다.

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

이렇게하면 charToFill을 사용하여 문자열을 사용하여 무제한 java8 스트림을 생성하고 출력을 길이로 제한하고 문자열 조이너 (새 학교)로 결과를 수집합니다.

String s = Stream.generate(() -> String.valueOf(charToFill)).limit(length).collect(Collectors.joining());

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

Google Guava를 사용한 솔루션

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

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();
}

뭐가 잘못 되었 니?


성능을 향상시키기 위해 다음과 같은 최대 길이를 알고있는 경우 사전 정의 된 단일 스팅을 가질 수 있습니다.

문자열 템플릿 = "###################################";

그런 다음 길이를 알면 부분 문자열을 수행하십시오.


Java 11에는 다음이 있습니다 repeat.

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

(작성 당시에는 변경 될 수 있습니다. )


달러를 사용하는 것은 간단합니다.

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

Apache Commons-Lang보다 선호하므로 Google Guava를 사용하는 솔루션 :

/**
 * 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);
}

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.

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);
  }
}

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.


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.


Mi solution :

  pw = "1321";
    if (pw.length() < 16){
      for(int x = pw.length() ; x < 16 ; x++){
        pw  += "*";
      }
    }

The output :

1321************

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);

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.

참고URL : https://stackoverflow.com/questions/1802915/java-create-a-new-string-instance-with-specified-length-and-filled-with-specif

반응형