- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
- Related Articles
- How to use Java string replace method?
- How to replace string using JavaScript RegExp?
- Replace Character in a String in Java without using replace() method
- How to replace characters on String in Java?
- How to replace multiple spaces in a string using a single space using Java regex?
- Program to replace all digits with characters using Python
- Java String replace() method example.
- How to replace all dots in a string using JavaScript?
- Replace a string using StringBuilder
- How to convert a double value into a Java String using format method?
- How to convert a double value into a Java String using append method?
- Using sed to Replace a Multi-Line String
- Java String replace(), replaceFirst() & replaceAll() Methods
- Replace String with another in java.
- How to match digits using Java Regular Expression (RegEx)

Advertisements