我被要求为类编写一个程序
- 接受了.txt文件
- 将文件中的数字0-9转换为等效文本(如果数字在句子开头,请使用大写字母)
- 将完成的句子打印到新文件中
示例:
The 8 eggs were separated into 3 groups.
将转换为:
The eight eggs were separated into three groups.
目前,我正在使用一个(非常)长的带有StringBuilder
的switch语句来完成任务:
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;
.....
}
有更先进/更有效的方法来完成这项任务吗?
您可能正在查找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(' '); }
您可以这样做。
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)];
}
您的整个程序已完成。
解释:
- 用空格分隔给定的语句
- 将单个单词存储到字符串数组中(标记[])
- 检查每个单词是否为数字
- 如果是数字,请转换为文本并将其添加到新语句中
- 如果是文本,请直接将其添加到新语句中
我会这样做。使用Character.isDigit
遍历字符以检查是否应该替换它们。如果是这样,只需使用(字符-'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