我被要求为课程编写一个程序:
示例:
The 8 eggs were separated into 3 groups.
将转换为:
The eight eggs were separated into three groups.
目前,我正在使用(非常)长的switch语句和StringBuilder
来完成任务:
switch(sb.charAt(i)){
case '0':
if (i == 0)
sb.replace(i, i+1, "Zero");
else
sb.replace(i, i+1, "zero");
break;
case '1':
if (i == 0)
sb.replace(i, i+1, "One");
else
sb.replace(i, i+1, "one");
break;
.....
}
有一种更高级/更有效的方法来完成这项任务吗?
答案 0 :(得分:4)
您可能正在寻找HashMap
。这有助于:
HashMap<String, String> DIGITS
并使用put("0", "zero"); put("1", "one"); //etc..
进行初始化。string.split(" ")
拆分输入字符串;这将创建一个这样的字符串数组:{"The","8","eggs",...}
。使用StringBuilder
建立答案:
for (String s : splitted) {
if (DIGITS.contains(s))
sb.append(DIGITS.get(s));
else
sb.append(s);
sb.append(' ');
}
答案 1 :(得分:0)
你可以这样做。
Sting[] token = statement.split(" ");
String newStatement = "";
for(int x=0; x<token.length; x++){
if(token[x].matches("[0-9]+"))
newStatement += convertToText(token[x]) + " ";
else
newStatement += token[x] + " ";
}
public static String converetToText(String str){
String[] text = {"zero", "one", "two", "three", "four", "five", "six", "seven". "eight", "nine"};
return text[Integer.parseInt(str)];
}
您的整个计划已经完成。
<强>解释强>
答案 2 :(得分:0)
我会做这样的事情。使用Character.isDigit
迭代字符以检查是否应替换它们。如果是这样,只需使用(character - '0'
)作为索引查找数组中的替换字符串:
String[] textArray = new String[]{ "zero", "one", "two",
"three", "four", "five",
"six", "seven", "eight", "nine" };
StringBuilder sb = new StringBuilder("abc 1 xyz 8");
System.out.println(sb);
for (int i=0; i<sb.length(); ++i) {
char c = sb.charAt(i);
if (Character.isDigit(c)) {
sb.replace(i, i+1, textArray[c - '0']);
}
}
System.out.println(sb);
输出是:
abc 1 xyz 8
abc one xyz eight