Anthony Chalk :
I need to read a String and then change all the numbers (from 0 - 12, inclusive) to the word for that number i.e. one, two,...twelve.
For example: This costs 1 dollar, but this is 12.
would be modified to: This costs one dollar, but this is twelve.
I tried this code
String[] line = s.split(" ");
StringBuilder stringBuilder = new StringBuilder();
for (String word : line){
try {
int i = Integer.parseInt(word);
if (map.containsKey(i)){
stringBuilder.append(map.get(i));
} else
stringBuilder.append(i);
} catch (Exception e) {
stringBuilder.append(word);
} finally {
stringBuilder.append(" ");
}
}
stringBuilder.deleteCharAt(stringBuilder.length()-1);
(the map just contains numbers 0-12 and their word equivalents)
The output was: This costs one dollar, but this is 12.
Obviously, the full-stop is the problem here; is there anyway I can ignore the punctuation?
Andrea :
EDIT: consider the logic in your parseInt with Regex:
int i = Integer.parseInt(word.replaceAll("\\p{Punct}", ""));
This will evaluate if the word is an integer by removing the punctuation before hands (but keeping the string as is).
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=417487&siteId=1