替代 switch -- 替换字符 [英] Alternative to switch -- replacing characters
本文介绍了替代 switch -- 替换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被要求为课程编写一个程序:
I was required to write a program for class which:
- 接受 .txt 文件
- 将文件中的数字 0-9 转换为对应的文本(如果数字在句首,请使用大写)
- 将完成的句子打印到新文件中
示例:
The 8 eggs were separated into 3 groups.
将转换为:
The eight eggs were separated into three groups.
<小时>
目前我正在使用带有 StringBuilder
的(非常)长的 switch 语句来完成任务:
Currently I am using a (very) long switch statement with a StringBuilder
to complete the task:
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;
.....
}
有更高级/更有效的方法来完成这项任务吗?
There is a more advanced/efficient way to accomplish this task?
推荐答案
可能您正在寻找 HashMap
.这可以帮助:
Probably you're looking for HashMap
. This can help:
- 创建静态
HashMap
并使用DIGITS put("0", "zero");把(1",一");//etc..
初始化它. - 使用
string.split(" ")
分割你的输入字符串;这将创建一个像这样的字符串数组:{"The","8","eggs",...}
. 使用
StringBuilder
构建答案:
- Create static
HashMap<String, String> DIGITS
and useput("0", "zero"); put("1", "one"); //etc..
to initialize it. - Split your input string using
string.split(" ")
; this will create an array of strings like this:{"The","8","eggs",...}
. Use
StringBuilder
to build an answer:
for (String s : splitted) {
if (DIGITS.contains(s))
sb.append(DIGITS.get(s));
else
sb.append(s);
sb.append(' ');
}
这篇关于替代 switch -- 替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文