Java – replace decimals 1 to 10 with names (“one”, “two”.)

I try to take a string and then return a string of numbers 1 to 10 and replace it with the words of these numbers For example:

Shall become:

So I did this:

import org.apache.commons.lang3.StringUtils;

String[] numbers = new String[] {"1","2","3","4","5","6","7","8","9","10"};
String[] words   = new String[]{"one","two","three","four","five","six","seven","eight","nine","ten"};
System.out.print(StringUtils.replaceEach(phrase,numbers,words));

The results are as follows:

So I tried a brute force approach. I'm sure it can be improved by regular expressions or more elegant string operations:

public class StringReplace {

  public static void main(String[] args) {
    String phrase = "I won 7 of the 10 games and received 30 dollars.";
    String[] sentenceWords = phrase.split(" ");
    StringBuilder sb = new StringBuilder();
    for (String s: sentenceWords) { 
      if (isNumeric(s)) { 
        sb.append(switchOutText(s));
      }

      else { 
        sb.append(s);
      }
      sb.append(" ");

    }
    System.out.print(sb.toString());
  }

  public static String switchOutText(String s) { 
    if (s.equals("1"))
      return "one";
    else if (s.equals("2"))
      return "two";
    else if (s.equals("3"))
      return "three";
    else if (s.equals("4"))
      return "four";
    else if (s.equals("5"))
      return "fivee";
    else if (s.equals("6"))
      return "six";
    else if (s.equals("7"))
      return "seven";
    else if (s.equals("8"))
      return "eight";
    else if (s.equals("9"))
      return "nine";        
    else if (s.equals("10"))
      return "ten";
    else
      return s;        
  }

  public static boolean isNumeric(String s) { 
    try { 
      int i = Integer.parseInt(s);
    }
    catch(NumberFormatException nfe) { 
      return false;
    }
    return true;
  }

}

Is there a better way? Of particular interest is the suggestion of regular expressions

Solution

This method uses regular expressions to match target numbers surrounded by non numbers (or start or end characters):

String[] words = { "one","ten" };
String phrase = "I won 7 of the 10 games and received 30 dollars.";

for (int i = 1; i <= 10; i++) {
  String pattern = "(^|\\D)" + i + "(\\D|$)";
  phrase = phrase.replaceAll(pattern,"$1" + words[i - 1] + "$2");
}

System.out.println(phrase);

This print:

If the number is the first or last word in the sentence, it will also be processed For example:

Translate correctly into

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>