有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是一种简单的重复字符串的方法

我正在寻找一个简单的commons方法或操作符,它允许我重复一些字符串n次。我知道我可以用for循环来写这个,但是我希望在必要的时候避免for循环,并且应该有一个简单的直接方法

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

repeated.equals("abcabcabc");

与以下内容相关:

repeat string javascript Create NSString by repeating another string a given number of times

已编辑

我尽量避免在不完全必要时使用for循环,因为:

  1. 它们增加了代码行数,即使它们被隐藏在另一个函数中

  2. 阅读我的代码的人必须弄清楚我在for循环中做了什么。即使它被注释并且有有有意义的变量名,他们仍然必须确保它没有做任何“聪明”的事情

  3. 程序员喜欢把聪明的东西放进循环中,即使我写它是为了“只做它想做的事”,但这并不妨碍有人来添加一些额外的聪明的“修复”

  4. 它们往往很容易出错。对于涉及索引的循环,往往会生成一个错误

  5. For循环经常重用相同的变量,这增加了很难找到范围错误的机会

  6. 对于循环,增加臭虫猎人必须寻找的地方的数量


共 (6) 个答案

  1. # 2 楼答案

    如果您使用的是Java<;=7,这是最“简洁”的:

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

    最后,对于Java11及更高版本,有一个新的repeat​(int count)方法专门用于此目的(link

    "abc".repeat(12);
    

    或者,如果您的项目使用java库,则有更多选项

    对于Apache Commons

    StringUtils.repeat("abc", 12);
    

    对于Google Guava

    Strings.repeat("abc", 12);
    
  2. # 3 楼答案

    String::repeat

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

    New in Java 11是方法^{},它完全满足您的要求:

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

    它的Javadoc说:

    /**
     * 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
     */ 
    
  3. # 4 楼答案

    Java 8的^{}提供了一种与^{}结合使用的简洁方法:

    // say hello 100 times
    System.out.println(String.join("", Collections.nCopies(100, "hello")));
    
  4. # 5 楼答案

    以下是最短的版本(需要Java 1.5+):

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

    其中n是要重复字符串的次数,s是要重复的字符串

    不需要导入或库

  5. # 6 楼答案

    以下是一种仅使用标准字符串函数而不使用显式循环的方法:

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