我可以在 Java 中乘以字符串来重复序列吗? [英] Can I multiply strings in Java to repeat sequences?
问题描述
我有类似以下内容:
int i = 3;
String someNum = "123";
我想将 i
"0" 附加到 someNum
字符串.它有什么方法可以像 Python 那样乘以一个字符串来重复它吗?
I'd like to append i
"0"s to the someNum
string. Does it have some way I can multiply a string to repeat it like Python does?
所以我可以走了:
someNum = sumNum + ("0" * 3);
或类似的东西?
在这种情况下,我的最终结果是:
Where, in this case, my final result would be:
123000".
推荐答案
在没有依赖的纯 Java 中最简单的方法是以下单行:
The easiest way in plain Java with no dependencies is the following one-liner:
new String(new char[generation]).replace(" ", "-")
用重复次数替换generation,用你想要重复的字符串(或字符)替换-".
Replace generation with number of repetitions, and the "-" with the string (or char) you want repeated.
所做的只是创建一个包含 n 个 0x00 字符的空字符串,其余的由内置的 String#replace 方法完成.
All this does is create an empty string containing n number of 0x00 characters, and the built-in String#replace method does the rest.
这是复制和粘贴的示例:
Here's a sample to copy and paste:
public static String repeat(int count, String with) {
return new String(new char[count]).replace(" ", with);
}
public static String repeat(int count) {
return repeat(count, " ");
}
public static void main(String[] args) {
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n) + " Hello");
}
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n, ":-) ") + " Hello");
}
}
这篇关于我可以在 Java 中乘以字符串来重复序列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!