java – 用名称替换小数1到10(“one”,“two”..)

前端之家收集整理的这篇文章主要介绍了java – 用名称替换小数1到10(“one”,“two”..)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图取一个字符串然后返回一个数字1到10的字符串替换为这些数字的单词.例如:

I won 7 of the 10 games and received 30 dollars.

应成为:

I won seven of the ten games and received 30 dollars.

所以我这样做了:

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

结果如下:

I won seven of the one0 games and received three0 dollars.

所以我尝试了一种蛮力方式,我确信可以通过正则表达式或更优雅的字符串操作来改进:

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

}

有没有更好的方法?特别感兴趣的是正则表达式的建议.

解决方法

方法使用正则表达式匹配由非数字(或开始或结束字符)包围的目标数字:
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);

这打印:

I won seven of the ten games and received 30 dollars.

如果数字是句子中的第一个或最后一个单词,它也会处理.例如:

9 cats turned on 100 others and killed 10

正确地翻译成

nine cats turned on 100 others and killed ten

原文链接:https://www.f2er.com/java/127566.html

猜你在找的Java相关文章