我可以将Java中的字符串乘以重复序列吗? [英] Can I multiply strings in Java to repeat sequences?

查看:480
本文介绍了我可以将Java中的字符串乘以重复序列吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

int i = 3;
String someNum = "123";

我想附加 i 0到s 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("\0", "-")

替换具有重复次数, - 包含您想要重复的字符串(或字符)。

Replace generation with number of repetitions, and the "-" with the string (or char) you want repeated.

所有这一切都是创建一个包含<的空字符串em> 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("\0", 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆