I was required to write a program for class which:
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?
Probably you're looking for HashMap
. This can help:
HashMap<String, String> DIGITS
and use put("0", "zero"); put("1", "one"); //etc..
put("0", "zero"); put("1", "one"); //etc..
put("0", "zero"); put("1", "one"); //etc..
to initialize it. 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(' '); }
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.