加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-05-25 15:23:27 所属栏目:Java 来源:互联网
导读:我试图取一个字符串然后返回一个数字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.Stri

我试图取一个字符串然后返回一个数字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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读