programing

간단한 문자열 반복 방법

prostudy 2022. 5. 24. 21:53
반응형

간단한 문자열 반복 방법

나는 약간의 문자열을 n번 반복할 수 있는 간단한 커먼스 방법이나 연산자를 찾고 있다.나는 내가 이것을 for loop을 사용해서 쓸 수 있다는 것을 알지만, 나는 필요할 때마다 루프를 피하는 것을 원하며, 어딘가에 간단한 직접 방법이 있어야 한다.

String str = "abc";
String repeated = str.repeat(3);

repeated.equals("abcabcabc");

관련 항목:

문자열 자바스크립트를 반복하다. 지정된 횟수만큼 다른 문자열을 반복하여 NSString 작성

편집됨

다음과 같은 이유로 루프가 완전히 필요하지 않을 때 루프를 피하려고 한다.

  1. 그것들은 다른 기능에 숨겨져 있더라도 코드 행의 수를 더한다.

  2. 누군가 내 코드를 읽으면 루프를 위해 내가 뭘 하고 있는지 알아내야 해코멘트를 하고 의미 있는 변수 이름을 가지고 있다고 해도, 그들은 여전히 그것이 "더 깨끗한" 어떤 것도 하고 있지 않다는 것을 확실히 해야 한다.

  3. 프로그래머들은 루프를 위해 영리한 것들을 넣는 것을 좋아하는데, 비록 내가 그것을 "그것이 의도된 대로만" 하도록 쓰더라도, 그것은 누군가가 와서 몇몇 영리한 "수정"을 추가하는 것을 막지 않는다.

  4. 그들은 종종 틀리기 쉽다.지수를 포함하는 루프는 하나의 버그에 의해 생성되는 경향이 있다.

  5. 루프는 동일한 변수를 자주 재사용하므로 범위 지정 버그를 찾기 어려울 가능성이 높아진다.

  6. 루프는 곤충 사냥꾼이 찾아야 하는 장소의 수를 증가시킨다.

다음은 최단 버전(Java 1.5+ 필요):

repeated = new String(new char[n]).replace("\0", s);

어디에n 및 을 반복할 수 있는 s반복할 문자열.

가져오기 또는 라이브러리가 필요하지 않음

Java <= 7>을 사용하는 경우, 다음과 같이 "concise"가 된다.

// create a string made up of n copies of string s
String.format("%0" + n + "d", 0).replace("0", s);

Java 8 이상에서는 보다 읽기 쉬운 방법이 있다.

// create a string made up of n copies of string s
String.join("", Collections.nCopies(n, s));

마지막으로 자바 11 이상에게는 새로운 것이 있다.repeat​(int count)이 목적을 위한 방법(링크)

"abc".repeat(12);

또는 프로젝트가 Java 라이브러리를 사용하는 경우 더 많은 옵션이 있다.

Apache Commons의 경우:

StringUtils.repeat("abc", 12);

Google Guava의 경우:

Strings.repeat("abc", 12);

String::repeat

". ".repeat(7)  // Seven period-with-space pairs: . . . . . . . 

Java 11의 New(New in Java 11의 새로운 기능)는 요청한 대로 정확하게 수행하는 방법이다.

String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

그것의 자바독은 다음과 같이 말한다.

/**
 * Returns a string whose value is the concatenation of this
 * string repeated {@code count} times.
 * <p>
 * If this string is empty or count is zero then the empty
 * string is returned.
 *
 * @param count number of times to repeat
 *
 * @return A string composed of this string repeated
 * {@code count} times or the empty string if this
 * string is empty or count is zero
 *
 * @throws IllegalArgumentException if the {@code count} is
 * negative.
 *
 * @since 11
 */ 

Commons Lang StringUtils.repeat()

사용량:

String str = "abc";
String repeated = StringUtils.repeat(str, 3);

repeated.equals("abcabcabc");

Java 8은 다음과 함께 이를 수행할 수 있는 깔끔한 방법을 제공한다.

// say hello 100 times
System.out.println(String.join("", Collections.nCopies(100, "hello")));

표준 문자열 기능만 사용하고 명시적 루프는 사용하지 않는 방법:

// create a string made up of  n  copies of  s
repeated = String.format(String.format("%%%ds", n), " ").replace(" ",s);

나처럼 아파치 커먼스가 아닌 구글 구아바를 사용하고 싶다면.반복 방법은 Guava String 클래스에서 사용할 수 있다.

Strings.repeat("-", 60);

과 함께, 당신은 또한 사용할 수 있다.Stream.generate.

import static java.util.stream.Collectors.joining;
...
String repeated = Stream.generate(() -> "abc").limit(3).collect(joining()); //"abcabcabc"

필요한 경우 간단한 유틸리티 방법으로 포장 가능:

public static String repeat(String str, int times) {
   return Stream.generate(() -> str).limit(times).collect(joining());
}

그래서 루프를 피하고 싶으세요?

여기 있다.

public static String repeat(String s, int times) {
    if (times <= 0) return "";
    else return s + repeat(s, times-1);
}

(물론 나는 이것이 추악하고 비효율적이라는 것을 알고 있지만 루프는 없다 :-p)

좀 더 심플하고 예뻐지고 싶어?jython 사용:

s * 3

편집: 약간 최적화:-D

public static String repeat(String s, int times) {
   if (times <= 0) return "";
   else if (times % 2 == 0) return repeat(s+s, times/2);
   else return s + repeat(s+s, times/2);
}

편집2: 4가지 주요 대안에 대한 빠르고 더러운 벤치마크를 해 보았지만, 여러 가지 입력에 대한 수단을 얻고 시간을 계획하기 위해 여러 번 실행할 시간이 없다...그러니 누군가 시도해보고 싶다면 여기 코드가 있다.

public class Repeat {
    public static void main(String[] args)  {
        int n = Integer.parseInt(args[0]);
        String s = args[1];
        int l = s.length();
        long start, end;

        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            if(repeatLog2(s,i).length()!=i*l) throw new RuntimeException();
        }
        end = System.currentTimeMillis();
        System.out.println("RecLog2Concat: " + (end-start) + "ms");

        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            if(repeatR(s,i).length()!=i*l) throw new RuntimeException();
        }               
        end = System.currentTimeMillis();
        System.out.println("RecLinConcat: " + (end-start) + "ms");

        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            if(repeatIc(s,i).length()!=i*l) throw new RuntimeException();
        }
        end = System.currentTimeMillis();
        System.out.println("IterConcat: " + (end-start) + "ms");

        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            if(repeatSb(s,i).length()!=i*l) throw new RuntimeException();
        }
        end = System.currentTimeMillis();
        System.out.println("IterStrB: " + (end-start) + "ms");
    }

    public static String repeatLog2(String s, int times) {
        if (times <= 0) {
            return "";
        }
        else if (times % 2 == 0) {
            return repeatLog2(s+s, times/2);
        }
        else {
           return s + repeatLog2(s+s, times/2);
        }
    }

    public static String repeatR(String s, int times) {
        if (times <= 0) {
            return "";
        }
        else {
            return s + repeatR(s, times-1);
        }
    }

    public static String repeatIc(String s, int times) {
        String tmp = "";
        for (int i = 0; i < times; i++) {
            tmp += s;
        }
        return tmp;
    }

    public static String repeatSb(String s, int n) {
        final StringBuilder sb = new StringBuilder();
        for(int i = 0; i < n; i++) {
            sb.append(s);
        }
        return sb.toString();
    }
}

2개의 인수가 필요하며, 첫 번째 인수는 반복 횟수(각 함수는 1..n부터 반복 시간 arg으로 실행됨)이고, 두 번째 인수는 반복할 문자열이다.

지금까지 다른 입력으로 실행된 시간을 신속하게 검사하면 다음과 같은 순위가 남는다(더 나쁜 것은 더 좋다).

  1. 반복 StringBuilder 추가(1x).
  2. 재귀적 연결 로그2 호출(~3배)
  3. 재귀적 연결 선형 호출(~30배)
  4. 반복 연결 선형(~45x)

나는 재귀 기능이 재귀보다 빠르다는 것을 전혀 짐작하지 못했을 것이다.for루프 :-o

재미있게 놀아라.

이것은 당신의 질문보다 적은 문자를 포함한다.

public static String repeat(String s, int n) {
    if(s == null) {
        return null;
    }
    final StringBuilder sb = new StringBuilder(s.length() * n);
    for(int i = 0; i < n; i++) {
        sb.append(s);
    }
    return sb.toString();
}

Fortran의 답변에 따르면, StringBuilder를 사용하는 다음과 같은 어음 버전이다.

public static void repeat(StringBuilder stringBuilder, String s, int times) {
    if (times > 0) {
        repeat(stringBuilder.append(s), s, times - 1);
    }
}

public static String repeat(String s, int times) {
    StringBuilder stringBuilder = new StringBuilder(s.length() * times);
    repeat(stringBuilder, s, times);
    return stringBuilder.toString();
}

달러 사용은 다음을 입력하는 것만큼 간단하다.

@Test
public void repeatString() {
    String string = "abc";
    assertThat($(string).repeat(3).toString(), is("abcabcabc"));
}

PS: 배열, 목록, 세트 등에 대해서도 반복 작업

나는 JDBC 목적을 위해 쉼표로 구분된 물음표 목록을 만드는 기능을 원했고, 이 게시물을 발견했다.그래서 나는 두 가지 변형을 가지고 어떤 변형이 더 잘 되는지 보기로 했다.100만 번을 반복한 결과, 정원이 다른 스트링빌더(StringBuilder)는 2초(fun1)가 걸렸고, 암호로 더 최적화한 버전(fun2)은 30초가 걸렸다.왜 또 암호화된 거야?

private static String fun1(int size) {
    StringBuilder sb = new StringBuilder(size * 2);
    for (int i = 0; i < size; i++) {
        sb.append(",?");
    }
    return sb.substring(1);
}

private static String fun2(int size) {
    return new String(new char[size]).replaceAll("\0", ",?").substring(1);
}

OOP 솔루션

거의 모든 답변이 해결책으로서 정적 기능을 제안하지만, (재사용성-청용성과 명확성을 위해) 나는 CharSequence-Classes에 대한 사용적합성을 개방하는 CharSequence-Classes를 통해 위임을 통해 해결책을 생각해냈다.

다음 클래스는 Sequarter-String/CharSequence와 함께 또는 사용하지 않고 사용할 수 있으며, "toString()"에 대한 각 호출은 최종 반복된 문자열을 구축한다.입력/분리기는 String-Class에 제한될 뿐만 아니라 CharSequence를 구현하는 모든 클래스(예: StringBuilder, StringBuffer 등)가 될 수 있다!

소스 코드:

/**
 * Helper-Class for Repeating Strings and other CharSequence-Implementations
 * @author Maciej Schuttkowski
 */
public class RepeatingCharSequence implements CharSequence {
    final int count;
    CharSequence internalCharSeq = "";
    CharSequence separator = "";
    /**
     * CONSTRUCTOR - RepeatingCharSequence
     * @param input CharSequence to repeat
     * @param count Repeat-Count
     */
    public RepeatingCharSequence(CharSequence input, int count) {
        if(count < 0)
            throw new IllegalArgumentException("Can not repeat String \""+input+"\" less than 0 times! count="+count);
        if(count > 0)
            internalCharSeq = input;
        this.count = count;
    }
    /**
     * CONSTRUCTOR - Strings.RepeatingCharSequence
     * @param input CharSequence to repeat
     * @param count Repeat-Count
     * @param separator Separator-Sequence to use
     */
    public RepeatingCharSequence(CharSequence input, int count, CharSequence separator) {
        this(input, count);
        this.separator = separator;
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        checkBounds(start);
        checkBounds(end);
        int subLen = end - start;
        if (subLen < 0) {
            throw new IndexOutOfBoundsException("Illegal subSequence-Length: "+subLen);
        }
        return (start == 0 && end == length()) ? this
                    : toString().substring(start, subLen);
    }
    @Override
    public int length() {
        //We return the total length of our CharSequences with the separator 1 time less than amount of repeats:
        return count < 1 ? 0
                : ( (internalCharSeq.length()*count) + (separator.length()*(count-1)));
    }
    @Override
    public char charAt(int index) {
        final int internalIndex = internalIndex(index);
        //Delegate to Separator-CharSequence or Input-CharSequence depending on internal index:
        if(internalIndex > internalCharSeq.length()-1) {
            return separator.charAt(internalIndex-internalCharSeq.length());
        }
        return internalCharSeq.charAt(internalIndex);
    }
    @Override
    public String toString() {
        return count < 1 ? ""
                : new StringBuilder(this).toString();
    }

    private void checkBounds(int index) {
        if(index < 0 || index >= length())
            throw new IndexOutOfBoundsException("Index out of Bounds: "+index);
    }
    private int internalIndex(int index) {
        // We need to add 1 Separator-Length to total length before dividing,
        // as we subtracted one Separator-Length in "length()"
        return index % ((length()+separator.length())/count);
    }
}

사용량-예:

public static void main(String[] args) {
    //String input = "12345";
    //StringBuffer input = new StringBuffer("12345");
    StringBuilder input = new StringBuilder("123");
    //String separator = "<=>";
    StringBuilder separator = new StringBuilder("<=");//.append('>');
    int repeatCount = 2;

    CharSequence repSeq = new RepeatingCharSequence(input, repeatCount, separator);
    String repStr = repSeq.toString();

    System.out.println("Repeat="+repeatCount+"\tSeparator="+separator+"\tInput="+input+"\tLength="+input.length());
    System.out.println("CharSeq:\tLength="+repSeq.length()+"\tVal="+repSeq);
    System.out.println("String :\tLength="+repStr.length()+"\tVal="+repStr);

    //Here comes the Magic with a StringBuilder as Input, as you can append to the String-Builder
    //and at the same Time your Repeating-Sequence's toString()-Method returns the updated String :)
    input.append("ff");
    System.out.println(repSeq);
    //Same can be done with the Separator:
    separator.append("===").append('>');
    System.out.println(repSeq);
}

예제-출력:

Repeat=2    Separator=<=    Input=123   Length=3
CharSeq:    Length=8    Val=123<=123
String :    Length=8    Val=123<=123
123ff<=123ff
123ff<====>123ff

JRE 클래스만 사용(시스템).arraycopy) 및 다음과 같은 내용을 작성할 수 있는 임시 개체 수를 최소화하기 위해 노력:

public static String repeat(String toRepeat, int times) {
    if (toRepeat == null) {
        toRepeat = "";
    }

    if (times < 0) {
        times = 0;
    }

    final int length = toRepeat.length();
    final int total = length * times;
    final char[] src = toRepeat.toCharArray();
    char[] dst = new char[total];

    for (int i = 0; i < total; i += length) {
        System.arraycopy(src, 0, dst, i, length);
    }

    return String.copyValueOf(dst);
}

편집

루프 없이 다음을 사용해 보십시오.

public static String repeat2(String toRepeat, int times) {
    if (toRepeat == null) {
        toRepeat = "";
    }

    if (times < 0) {
        times = 0;
    }

    String[] copies = new String[times];
    Arrays.fill(copies, toRepeat);
    return Arrays.toString(copies).
              replace("[", "").
              replace("]", "").
              replaceAll(", ", "");
}

편집 2

컬렉션을 사용하는 것이 훨씬 더 짧다:

public static String repeat3(String toRepeat, int times) {
    return Collections.nCopies(times, toRepeat).
           toString().
           replace("[", "").
           replace("]", "").
           replaceAll(", ", "");
}

그러나 나는 여전히 첫번째 버전을 좋아한다.

가장 짧은 방법은 아니지만 StringBuilder를 사용하는 것이 가장 빠른 방법이라고 생각한다.

 /**
   * Repeat a String as many times you need.
   *
   * @param i - Number of Repeating the String.
   * @param s - The String wich you want repeated.
   * @return The string n - times.
   */
  public static String repeate(int i, String s) {
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < i; j++)
      sb.append(s);
    return sb.toString();
  }

속도가 문제라면 메모리 복사를 가능한 적게 사용해야 한다.따라서 그것은 차자의 배열과 함께 작업해야 한다.

public static String repeatString(String what, int howmany) {
    char[] pattern = what.toCharArray();
    char[] res = new char[howmany * pattern.length];
    int length = pattern.length;
    for (int i = 0; i < howmany; i++)
        System.arraycopy(pattern, 0, res, i * length, length);
    return new String(res);
}

속도를 테스트하기 위해 스턴빌더를 사용하는 유사한 최적의 방법은 다음과 같다.

public static String repeatStringSB(String what, int howmany) {
    StringBuilder out = new StringBuilder(what.length() * howmany);
    for (int i = 0; i < howmany; i++)
        out.append(what);
    return out.toString();
}

테스트할 코드:

public static void main(String... args) {
    String res;
    long time;

    for (int j = 0; j < 1000; j++) {
        res = repeatString("123", 100000);
        res = repeatStringSB("123", 100000);
    }

    time = System.nanoTime();
    res = repeatString("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatString: " + time);

    time = System.nanoTime();
    res = repeatStringSB("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatStringSB: " + time);

}

내 시스템의 실행 결과는 다음과 같다.

elapsed repeatString: 6006571
elapsed repeatStringSB: 9064937

루프에 대한 테스트는 JIT를 시작하고 최적의 결과를 얻기 위함입니다.

간단한 한 줄 솔루션:
Java 8 필요

Collections.nCopies( 3, "abc" ).stream().collect( Collectors.joining() );

가독성과 휴대성을 위해:

public String repeat(String str, int count){
    if(count <= 0) {return "";}
    return new String(new char[count]).replace("\0", str);
}

성능이 걱정되는 경우 루프 내에서 StringBuilder를 사용하고 루프 종료 시 .toString()을 실행하십시오.직접 Util 클래스를 작성하여 재사용하십시오. 코드 최대 5행.

나는 이 질문이 정말 즐겁다.많은 지식과 스타일이 있다.그래서 내 로큰롤을 보여주지 않고는 떠날 수 없다.)

{
    String string = repeat("1234567890", 4);
    System.out.println(string);
    System.out.println("=======");
    repeatWithoutCopySample(string, 100000);
    System.out.println(string);// This take time, try it without printing
    System.out.println(string.length());
}

/**
 * The core of the task.
 */
@SuppressWarnings("AssignmentToMethodParameter")
public static char[] repeat(char[] sample, int times) {
    char[] r = new char[sample.length * times];
    while (--times > -1) {
        System.arraycopy(sample, 0, r, times * sample.length, sample.length);
    }
    return r;
}

/**
 * Java classic style.
 */
public static String repeat(String sample, int times) {
    return new String(repeat(sample.toCharArray(), times));
}

/**
 * Java extreme memory style.
 */
@SuppressWarnings("UseSpecificCatch")
public static void repeatWithoutCopySample(String sample, int times) {
    try {
        Field valueStringField = String.class.getDeclaredField("value");
        valueStringField.setAccessible(true);
        valueStringField.set(sample, repeat((char[]) valueStringField.get(sample), times));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

마음에 드세요?

public static String repeat(String str, int times) {
    int length = str.length();
    int size = length * times;
    char[] c = new char[size];
    for (int i = 0; i < size; i++) {
        c[i] = str.charAt(i % length);
    }
    return new String(c);
}

심플 루프

public static String repeat(String string, int times) {
    StringBuilder out = new StringBuilder();
    while (times-- > 0) {
        out.append(string);
    }
    return out.toString();
}

이 방법을 사용해 보십시오.

public static char[] myABCs = {'a', 'b', 'c'};
public static int numInput;
static Scanner in = new Scanner(System.in);

public static void main(String[] args) {
    System.out.print("Enter Number of Times to repeat: ");
    numInput = in.nextInt();
    repeatArray(numInput);
}

public static int repeatArray(int y) {
    for (int a = 0; a < y; a++) {
        for (int b = 0; b < myABCs.length; b++) {
            System.out.print(myABCs[b]);                
        }
        System.out.print(" ");
    }
    return y;
}

재귀(재귀)를 사용하여 다음 작업을 수행할 수 있다(제3의 연산자 사용, 최대 한 줄).

public static final String repeat(String string, long number) {
    return number == 1 ? string : (number % 2 == 0 ? repeat(string + string, number / 2) : string + repeat(string + string, (number - 1) / 2));
}

알아, 추하고 효율적이지 않을 수도 있지만, 한 줄이야!

출력 문자열의 길이만 알고 있으면(입력 문자열의 길이로 나눌 수 없는 경우도 있음) 다음 방법을 사용하십시오.

static String repeat(String s, int length) {
    return s.length() >= length ? s.substring(0, length) : repeat(s + s, length);
}

사용 데모:

for (int i = 0; i < 50; i++)
    System.out.println(repeat("_/‾\\", i));

빈손으로 사용하지 마십시오.s그리고length> 0, 이 경우에는 원하는 결과를 얻을 수 없기 때문에.

루프를 사용하지 않으려는 당신의 바람에도 불구하고, 나는 당신이 루프를 사용해야 한다고 생각한다.

String repeatString(String s, int repetitions)
{
    if(repetitions < 0) throw SomeException();

    else if(s == null) return null;

    StringBuilder stringBuilder = new StringBuilder(s.length() * repetitions);

    for(int i = 0; i < repetitions; i++)
        stringBuilder.append(s);

    return stringBuilder.toString();
}

루프를 사용하지 않는 이유는 좋지 않다.당신의 비판에 대응하여:

  1. 당신이 어떤 해결책을 사용하든 거의 확실히 이것보다 더 길어질 것이다.사전 제작된 기능을 사용하면 더 많은 커버에 넣을 수 있다.
  2. 누군가 네 코드를 읽으면 네가 그 비루프에서 뭘 하고 있는지 알아내야 할 거야.포루프(for-loop)가 이것을 하는 관용적인 방법이라는 점에서 포루프를 가지고 했는지를 알아내는 것이 훨씬 쉬울 것이다.
  3. 그래, 누군가는 영리한 것을 덧붙일 수도 있지만, 허풍을 피함으로써 당신은 영리한 것을 하고 있는 것이다.그것은 우연히 자기 발을 쏘지 않기 위해 일부러 자기 발을 쏘는 것과 같다.
  4. 한 번의 시험으로 잡기가 아주 쉬운 실수도 없이 한 번의 오차도 쉽게 잡을 수 있다.코드를 테스트해야 한다는 점을 감안할 때, 한 번에 하나씩의 오차는 쉽게 수정하고 포착할 수 있어야 한다.그리고 주목할 필요가 있다: 위의 코드에 오프바이더 오류가 포함되어 있지 않다.루프는 맞추기가 쉽기 때문이다.
  5. 따라서 변수를 재사용하지 마십시오.그건 약탈자의 잘못이 아니야.
  6. 다시 말하지만, 당신이 사용하는 해결책도 마찬가지다.그리고 내가 전에 말했듯이, 곤충 사냥꾼은 아마도 당신이 포루프를 가지고 이것을 하기를 기대하고 있을 것이다. 그래서 만약 당신이 포루프를 사용한다면 그들은 그것을 찾는데 더 쉬운 시간을 가질 것이다.

다음은 최신 Stringutils.java StringUtils.java StringUtils.java 입니다.

    public static String repeat(String str, int repeat) {
    // Performance tuned for 2.0 (JDK1.4)

    if (str == null) {
        return null;
    }
    if (repeat <= 0) {
        return EMPTY;
    }
    int inputLength = str.length();
    if (repeat == 1 || inputLength == 0) {
        return str;
    }
    if (inputLength == 1 && repeat <= PAD_LIMIT) {
        return repeat(str.charAt(0), repeat);
    }

    int outputLength = inputLength * repeat;
    switch (inputLength) {
        case 1 :
            return repeat(str.charAt(0), repeat);
        case 2 :
            char ch0 = str.charAt(0);
            char ch1 = str.charAt(1);
            char[] output2 = new char[outputLength];
            for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
                output2[i] = ch0;
                output2[i + 1] = ch1;
            }
            return new String(output2);
        default :
            StringBuilder buf = new StringBuilder(outputLength);
            for (int i = 0; i < repeat; i++) {
                buf.append(str);
            }
            return buf.toString();
    }
    }

이렇게 클 필요도 없고, 이렇게 만들 수도 있고, 프로젝트의 유틸리티 클래스에 복사하여 붙여넣을 수도 있다.

    public static String repeat(String str, int num) {
    int len = num * str.length();
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < times; i++) {
        sb.append(str);
    }
    return sb.toString();
    }

그래서 e5, 나는 이것을 하는 가장 좋은 방법은 위에 언급된 코드, 또는 여기에 있는 어떤 답을 사용하는 것이라고 생각한다. 그러나 커먼즈 랭귀지는 작은 프로젝트라면 너무 크다.

나는 당신이 원하는 것과 같은 재귀적인 방법을 만들었다.얼마든지 이걸 써도용할 수 있다.

public String repeat(String str, int count) {
    return count > 0 ?  repeat(str, count -1) + str: "";
}

나는 같은 대답을 가지고 있다 자바에서 문자열을 곱해서 시퀀스를 반복할 수 있는가?

public static String rep(int a,String k)

       {
           if(a<=0)
                return "";
           else 
           {a--;
               return k+rep(a,k);
       }

원하는 목표에 대해 이 재귀적 방법을 사용할 수 있다.

참조URL: https://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string

반응형