我会推荐一个 StringTokenizer。这将允许您一个一个地分析每个单词。
StringTokenizer st = new StringTokenizer(yourString);
String firstNumber = st.nextToken();
String secondNumber = st.nextToken();
比较这些数字的一个好方法是设置数组,其索引以某种方式对应于它们的值(即“一”将指向 DIGITS[0])。
public static final String[] DIGITS = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", null};
public static final String[] TENS = {null, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", null};
public static final String[] TEENS = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
剧透警告:下面是我最近写的一个粗略的方法,用于将一个数字(低于 1 万亿)从一串单词转换为一个数字。可能是您正在寻找的。同样,如果这是为了自学,我不建议复制/粘贴代码,而是了解它是如何工作的。
public static final String[] DIGITS = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", null};
public static final String[] TENS = {null, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", null};
public static final String[] TEENS = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
public static final String[] MAGNITUDES = {null, null, null, "thousand", null, null, "million", null, null, "billion", null, null, "trillion"};
public static final String[] ZERO = {"zero", "oh"};
public static double wordToNumber(String input) {
double result = 0;
String[] decimal = input.split("point");
StringTokenizer set = new StringTokenizer(decimal[0]);
boolean negative = false;
if (input.contains("negative")) {
negative = true;
}
double group = 0;
while (set.hasMoreTokens()) {
String word = set.nextToken();
for (int i = 0; i < MAGNITUDES.length; i += 3) {
if (word.equals(MAGNITUDES[i])) {
group = group * Math.pow(10, i);
result = result + group;
group = 0;
}
}
if (word.equals("hundred")) {
group = group * 100;
}
else {
for (int i = 0; i < 10; i++) {
if (word.equals(DIGITS[i])) {
group = group + i + 1;
}
if (word.equals(TEENS[i])) {
group = group + 10 + i;
}
if (word.equals(TENS[i])) {
group = group + 10 * (i + 1);
}
}
}
}
result = result + group;
if (decimal.length > 1) {
StringTokenizer hang = new StringTokenizer(decimal[1]);
int n = -1;
while (hang.hasMoreTokens()) {
String word = hang.nextToken();
for (int i = 0; i < 10; i++) {
if (word.equals(DIGITS[i])) {
result = result + (i + 1) * Math.pow(10, n);
}
}
n--;
}
}
if (negative) {
result = result * (-1);
}
return result;
}
输入“负七千八百三十万六百零五零七”返回值的双倍 -78380601.507。