How to replace Digits into String using Java?


For this purpose, we create an object of HashMap class which is defined in java.util package

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

This hashmap object associates each digit with its corresponding word representation

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

Initialize an empty string object.

String newstr="";

Next, run a for loop over the length of given string and extract each character by substring() method of String class.

Check if the character exists as a key in map object by containsKey() method. If it does, using it as key, obtain its value component in map and appenf\d to the new string. If not append the character itself to the new string. The complete code is as below:

Example

Live Demo

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);
   }
}

The output is as desired:

Output

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

Updated on: 20-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements