生成 n 个重复字符的字符串的最简单方法是什么?

发布于 2024-11-30 03:31:26 字数 239 浏览 4 评论 0原文

给定一个字符 c 和一个数字 n,如何创建一个由 n 个重复的 c 组成的字符串?手动执行太麻烦了:

StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();

肯定有一些静态库函数已经为我执行此操作了吗?

Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();

Surely there is some static library function that already does this for me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

叹倦 2024-12-07 03:31:26
int n = 10;
char[] chars = new char[n];
Arrays.fill(chars, 'c');
String result = new String(chars);

编辑:

这个答案已经提交九年了,但它仍然时不时地引起一些关注。与此同时,Java 8 引入了函数式编程功能。给定一个 char c 和所需的重复次数 count,下面的单行代码可以执行与上面相同的操作。

String result = IntStream.range(1, count).mapToObj(index -> "" + c).collect(Collectors.joining());

但请注意,它比数组方法慢。除了最苛刻的情况外,这几乎不重要。除非它是在每秒执行数千次的某些代码中,否则不会有太大区别。这也可以与字符串而不是字符一起使用来重复多次,因此更加灵活。不需要第三方库。

int n = 10;
char[] chars = new char[n];
Arrays.fill(chars, 'c');
String result = new String(chars);

EDIT:

It's been 9 years since this answer was submitted but it still attracts some attention now and then. In the meantime Java 8 has been introduced with functional programming features. Given a char c and the desired number of repetitions count the following one-liner can do the same as above.

String result = IntStream.range(1, count).mapToObj(index -> "" + c).collect(Collectors.joining());

Do note however that it is slower than the array approach. It should hardly matter in any but the most demanding circumstances. Unless it's in some piece of code that will be executed thousands of times per second it won't make much difference. This can also be used with a String instead of a char to repeat it a number of times so it's a bit more flexible. No third-party libraries needed.

半世晨晓 2024-12-07 03:31:26

如果可以,请使用 StringUtils 来自 Apache Commons Lang

StringUtils.repeat("ab", 3);  //"ababab"

If you can, use StringUtils from Apache Commons Lang:

StringUtils.repeat("ab", 3);  //"ababab"
童话里做英雄 2024-12-07 03:31:26

为了了解速度损失,我测试了两个版本,一个使用 Array.fill,另一个使用 StringBuilder。

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

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

使用

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

(注意main函数中的循环是为了启动JIT)

结果如下:

elapsed repeat  : 65899
elapsed repeatSB: 305171

这是一个巨大差异

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

小红帽 2024-12-07 03:31:26

Java SE 11

String#repeat (int count) 作为 Java SE 11 的一部分引入,使其变得非常容易实现。

演示:

public class Main {
    public static void main(String[] args) {
        char ch = 'c';
        int n = 20;
        String result = String.valueOf(ch).repeat(n);
        System.out.println(result);
    }
}

输出:

cccccccccccccccccccc

Java SE 11

String#repeat​(int count), introduced as part of Java SE 11, makes it quite easy to do.

Demo:

public class Main {
    public static void main(String[] args) {
        char ch = 'c';
        int n = 20;
        String result = String.valueOf(ch).repeat(n);
        System.out.println(result);
    }
}

Output:

cccccccccccccccccccc
℡寂寞咖啡 2024-12-07 03:31:26

看看这个示例

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

答案,它是在java中重复字符串的简单方法,所以在那里投票

take look at this sample

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

answer taken form Simple way to repeat a String in java so vote up there

心是晴朗的。 2024-12-07 03:31:26

这是一个基于标准二进制供电算法的 O(logN) 方法:

public static String repChar(char c, int reps) {
    String adder = Character.toString(c);
    String result = "";
    while (reps > 0) {
        if (reps % 2 == 1) {
            result += adder;
        }
        adder += adder;
        reps /= 2;
    }        
    return result;
}

reps 的负值返回空字符串。

Here is an O(logN) method, based on the standard binary powering algorithm:

public static String repChar(char c, int reps) {
    String adder = Character.toString(c);
    String result = "";
    while (reps > 0) {
        if (reps % 2 == 1) {
            result += adder;
        }
        adder += adder;
        reps /= 2;
    }        
    return result;
}

Negative values for reps return the empty string.

提笔落墨 2024-12-07 03:31:26

只需将其添加到您自己的...

public static String generateRepeatingString(char c, Integer n) {
    StringBuilder b = new StringBuilder();
    for (Integer x = 0; x < n; x++)
        b.append(c);
    return b.toString();
}

或者 Apache commons 有一个可以添加的实用程序类。

Just add it to your own...

public static String generateRepeatingString(char c, Integer n) {
    StringBuilder b = new StringBuilder();
    for (Integer x = 0; x < n; x++)
        b.append(c);
    return b.toString();
}

Or Apache commons has a utility class you can add.

婴鹅 2024-12-07 03:31:26

我添加另一种方法来解决它:

public String buildString(Character character, int nTimes) {
    return String.format("%" + nTimes + "s", " ").replace(' ', character);
}

I am adding another way to solve it:

public String buildString(Character character, int nTimes) {
    return String.format("%" + nTimes + "s", " ").replace(' ', character);
}
救赎№ 2024-12-07 03:31:26

如果您不是使用 Java 11+(否则我会选择 Arvind Kumar Avinash 的答案),您也可以结合 String#join(CharSequence, IterableCollections#nCopies( int,T)

String result = String.join("", Collections.nCopies(c, n));

If you are not on Java 11+ (otherwise I would go with Arvind Kumar Avinash's answer), you can also combine String#join(CharSequence, Iterable<? extends CharSequence> and Collections#nCopies(int, T):

String result = String.join("", Collections.nCopies(c, n));
も让我眼熟你 2024-12-07 03:31:26

一个简单而干净的解决方案是使用 String.format,然后用所需的字符替换字符。

String.format("%5s", "").replace(' ', '#')
// Output : #####

如果您使用的是 Java 11,

则只需使用 String.repeat()

"#".repeat(5)

A simple and clean solution would be to use String.format and then replace characters with desired character.

String.format("%5s", "").replace(' ', '#')
// Output : #####

If you are using Java 11

you can just use String.repeat()

"#".repeat(5)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文