如何使用 Java 將數字替換為字串?


為此,我們建立了一個 HashMap 類的物件,該物件在 **java.util** 包中定義

Map<String, String> map = new HashMap<String, String>();

這個 HashMap 物件將每個數字與其對應的單詞表示相關聯

map.put("0", "zero");

初始化一個空的字串物件。

String newstr="";

接下來,在給定字串的長度上執行一個 for 迴圈,並使用 String 類的 substring() 方法提取每個字元。

透過 containsKey() 方法檢查字元是否存在於對映物件中。如果存在,使用它作為鍵,獲取其對映中的值元件並追加到新字串。如果沒有,則將字元本身追加到新字串。完整程式碼如下

例項

線上演示

import java.util.*;
public class test {
   public static void main(String args[]) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("0", "zero");
      map.put("1", "one");
      map.put("2", "two");
      map.put("3", "three");
      map.put("4", "four");
      map.put("5", "five");
      map.put("6", "six");
      map.put("7", "seven");
      map.put("8", "eight");
      map.put("9", "nine");
      String s="I have 3 Networking books, 0 Database books, and 8 Programming books.";
      String newstr="";
      for (int i=0;i<s.length();i++) {
         String k=s.substring(i,i+1);
         if (map.containsKey(k)) {
            String v=map.get(k);
            newstr=newstr+v;
         } else
         newstr=newstr+k;
      }
      System.out.println(newstr);
   }
}

輸出按需提供

輸出

I have three Networking books, zero Database books, and eight Programming books.

更新日期:2020 年 6 月 20 日

1 千次以上瀏覽

開始您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.