Java: String - add character n-times [duplicate]

2020-02-26 14:08发布

Is there a simple way to add a character or another String n-times to an existing String? I couldn’t find anything in String, Stringbuilder, etc.

标签: java string
15条回答
等我变得足够好
2楼-- · 2020-02-26 14:29

To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.

public static String repeat(char what, int howmany) {
    char[] chars = new char[howmany];
    Arrays.fill(chars, what);
    return new String(chars);
}

and

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

using

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

    for (int j = 0; j < 1000; j++) {
        res = repeat(' ', 100000);
        res = repeatSB(' ', 100000);
    }
    time = System.nanoTime();
    res = repeat(' ', 100000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeat: " + time);

    time = System.nanoTime();
    res = repeatSB(' ', 100000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatSB: " + time);
}

(note the loop in main function is to kick in JIT)

The results are as follows:

elapsed repeat: 65899
elapsed repeatSB: 305171

It is a huge difference

查看更多
戒情不戒烟
3楼-- · 2020-02-26 14:33

You can use Guava's Strings.repeat method:

String existingString = ...
existingString += Strings.repeat("foo", n);
查看更多
唯我独甜
4楼-- · 2020-02-26 14:36

Here is a simple way..

for(int i=0;i<n;i++)
{
  yourString = yourString + "what you want to append continiously";
}
查看更多
5楼-- · 2020-02-26 14:37

You are able to do this using Java 8 stream APIs. The following code creates the string "cccc" from "c":

String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));
查看更多
▲ chillily
6楼-- · 2020-02-26 14:37

Use this:

String input = "original";
String newStr = "new"; //new string to be added
int n = 10 // no of times we want to add
input = input + new String(new char[n]).replace("\0", newStr);
查看更多
倾城 Initia
7楼-- · 2020-02-26 14:37
public String appendNewStringToExisting(String exisitingString, String newString, int number) {
    StringBuilder builder = new StringBuilder(exisitingString);
    for(int iDx = 0; iDx < number; iDx++){
        builder.append(newString);
    }
    return builder.toString();
}
查看更多
登录 后发表回答