Replaces the numbers 0..9 in a string with the respective English word. - Java java.lang

Java examples for java.lang:int Format

Description

Replaces the numbers 0..9 in a string with the respective English word.

Demo Code

//    This program is free software: you can redistribute it and/or modify
//package com.java2s;

public class Main {
    /**//ww w .j  av a 2  s  . co  m
     * Replaces the numbers 0..9 in a string with the 
     * respective English word. All other characters will
     * not be changed, e.g. '12.3' --> 'onetwo.three'. 
     * @param num input string with numeric characters
     * @return num with numeric characters replaced
     */
    public static String spellOutNumber(String num) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num.length(); i++) {
            char ch = num.charAt(i);
            switch (ch) {
            case '0':
                sb.append("zero");
                break;
            case '1':
                sb.append("one");
                break;
            case '2':
                sb.append("two");
                break;
            case '3':
                sb.append("three");
                break;
            case '4':
                sb.append("four");
                break;
            case '5':
                sb.append("five");
                break;
            case '6':
                sb.append("six");
                break;
            case '7':
                sb.append("seven");
                break;
            case '8':
                sb.append("eight");
                break;
            case '9':
                sb.append("nine");
                break;
            default:
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}

Related Tutorials