问题
I was required to write a program for class which:
- Accepted a .txt file
- Convert numbers 0-9 in the file to their text equivalent (if the number is at beginning of sentence, use uppercase)
- Print the finished sentences to a new file
Example:
The 8 eggs were separated into 3 groups.
Would be converted to:
The eight eggs were separated into three groups.
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?
回答1:
Probably you're looking for HashMap
. This can help:
- 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(' '); }
回答2:
You can do it this way.
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)];
}
Your entire program is completed.
Explanation:
- Split the given statement by spaces.
- Store individual word into a string array (token[])
- Check each individual word whether it is a number
- If it is a number convert to text and add it to new statement.
- If it is a text add it straight into your new statement.
回答3:
I would do something like this. Iterate through the characters using Character.isDigit
to check if they should be replaced. If so simply look up the replacement string in an array using (character - '0'
) as the index:
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);
Output is:
abc 1 xyz 8
abc one xyz eight
来源:https://stackoverflow.com/questions/28799408/alternative-to-switch-replacing-characters