Java中的乘法字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24454552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:18:06  来源:igfitidea点击:

Multiply string in Java

javapythonstring

提问by user3779568

In Python I can do this: print("a" * 2);

在 Python 中,我可以这样做: print("a" * 2);

Output = aa

输出 = aa

Is there a way in Java to do the same without loops?

Java中有没有办法在没有循环的情况下做同样的事情?

回答by Ian Knight

Try this:

尝试这个:

String buildString(char c, int n) {
    char[] arr = new char[n];
    Arrays.fill(arr, c);
    return new String(arr);
}

Arrays.fill()is a standard API methodthat assigns the given value to every element of the given array. I guess technically it'll be looping 'inside', in order to achieve this, but from the perspective of your program you've avoided looping.

Arrays.fill()是一种标准 API 方法,它将给定值分配给给定数组的每个元素。我想从技术上讲,它会在“内部”循环,以实现这一点,但从您的程序的角度来看,您已经避免了循环。

回答by Mike Elofson

While Java does not have a built in method of doing this, you can very easily accomplish this with a few lines of code using a StringBuilder.

虽然 Java 没有内置的方法来执行此操作,但您可以使用StringBuilder.

public static void main(String[] args) throws Exception {

    System.out.println(stringMultiply("a", 2));
}

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

The function stringMultiplyabove does essentially the same thing. It will loop ntimes (the number to multiply) and append the Stringsto the StringBuildereach loop. My assumption is that pythonuses the same logic for this, it is just a built in functionality, so your timing should not be too much different writing your own function.

stringMultiply上面的函数基本上做了同样的事情。它将循环n次数(要相乘的数字)并将 附加StringsStringBuilder每个循环中。我的假设是为此python使用相同的逻辑,它只是一个内置功能,因此您编写自己的function.