如何用Java中的字符串替换数值

时间:2014-10-16 05:59:36

标签: java printing output

我想打印" Two"代替2和"四"在FOR循环中用Java代替4,同时打印从1到50的数字。

例如:

1
Two
3
Four
5
.
.
.
1Four
15
.
.
.
Two1
TwoTwo
Two3
TwoFour
.
.
.
50

1 个答案:

答案 0 :(得分:0)

Java 8解决方案:

public class Play {

    public static void main(String[] args) {
        rangeClosed(1, 50).forEach(Play::twoOrFour);
    }

    public static void twoOrFour(long n) {
        String result = n + "";
        if (n % 10  == 2) {
            n /= 10;
            result = (n == 0 ? "" : n) + "two"; // the ternary exp: an ugly patch to get rid of the "0" in the first two cases
        } else if (n % 10 == 4) {
            n /= 10;
            result = (n == 0 ? "" : n) + "four";
        }
        System.out.print(result + " ");
    }
}

<强>输出

1 two 3 four 5 6 7 8 9 10 11 1two 13 1four 15 16 17 18 19 20 21 2two 23 2four 25 26 27 28 29 30 31 3two 33 3four 35 36 37 38 39 40 41 4two 43 4four 45 46 47 48 49 50

<强>更新
如果您想将任何出现的“2”替换为“2”而将“4”替换为“4”,则引用的方法可以更简单:

public static void twoOrFour(long n) {
    String result = n + "";
    result = result.replaceAll("2", "two").replaceAll("4", "four");
    System.out.print(result + " ");
}

将输出:

1 two 3 four 5 6 7 8 9 10 11 1two 13 1four 15 16 17 18 19 two0 two1 twotwo two3 twofour two5 two6 two7 two8 two9 30 31 3two 33 3four 35 36 37 38 39 four0 four1 fourtwo four3 fourfour four5 four6 four7 four8 four9 50

或者如果要更有趣 - 它可以在单行中完成:

rangeClosed(1, 50).forEach((x)-> System.out.print((x + " ").replaceAll("2", "two").replaceAll("4", "four")));