Is there a way to convert an English string
representation of an integer (e.g. "one hundred eighty") to an integer? As expected Integer.parseInt("thirty five")
threw a NumberFormatException
. Is there a built in function in Java to do this?
Asked
Active
Viewed 1,185 times
3
-
No, there is not built-in info for this. Instead, create your own map and parse the string manually or search for such implementation on the net. – Luiggi Mendoza Jul 31 '14 at 19:19
-
1There's been some interesting discussion on the reverse algorithm here: http://stackoverflow.com/questions/3911966/how-to-convert-number-to-words-in-java Maybe that can help you get started. – Akshay Jul 31 '14 at 19:19
-
1I would vote to close as duplicate, but that other one is also closed – James Kingsbery Jul 31 '14 at 19:43
2 Answers
4
No.
No, there is no built-in functionality to achieve this.
1. Approach: HashMap
You can use a HashMap to store the String, Integer pair (e.g.: "twenty" and 20).
HashMap<String, Integer> numbers = new HashMap<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
...
numbers.put("nine", 9);
numbers.put("ten", 10);
numbers.put("eleven", 11);
...
numbers.put("twenty", 20);
numbers.put("thirty", 30);
...
Then you can simply parse it via numbers.get(..) and add that number to your resulting number.
public int getNumber(String str)
{
int number = 0;
String[] parts = str.split(" ");
for (String number : parts)
{
if (numbers.contains(number)
{
number += parts.get(number);
}
}
return number;
}
2. Approach: ArrayList
You can create an ArrayList like
ArrayList<String> numbers = new ArrayList<String>;
numbers.add("zero");
numbers.add("one");
...
numbers.add("eight");
numbers.add("nine");
numbers.add("ten");
...
Then you could build your own function to parse a String to those numbers by looking them up in this ArrayList (their index is the resulting number).
public int getNumber(String str)
{
int number = 0;
String[] parts = str.split(" ");
for (String number : parts)
{
if (numbers.contains(number)
{
number += parts.indexof(number);
}
}
return number;
}
See also

Community
- 1
- 1

flotothemoon
- 1,882
- 2
- 20
- 37
0
Try to split the String by it's white spaces, then replace each word for it's corresponding number.
You can have a Map<String, Integer>
with the words and numbers.

MarcioB
- 1,538
- 1
- 9
- 11
-
@1337 I think your ArrayList implementation has a problem, but I can't comment on your answer. For the input "one hundred eighty" it would return '10080', wouldn't it? – MarcioB Jul 31 '14 at 20:33
-
You are absolutely right, the ArrayList implementation has flaws yeah, that's why I included the HashMap implementation too :) – flotothemoon Aug 01 '14 at 06:26
-
-
1I don't want to edit that part out because it is another interesting approach, I like the idea to use index-of for that - can be useful for some other things too :) – flotothemoon Aug 01 '14 at 11:18