簡體   English   中英

如何在Java中用字符串替換數字值

[英]How do I replace a numeric value with a string in Java

我想在FOR循環中在Java中將2替換為2,將4替換為4,同時將1到50的數字打印出來。

例如:

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

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”,而用“四個”替換出現的“ 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")));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM