java - 用数字作为单词比较两个字符串

标签 java string numbers string-comparison

我得到了数字作为单词:

{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
数字最多只有 10 个。我的任务是将给定的两个输入字符串相互比较。
当您比较两个数字时,它基本上应该起作用:
compare(1, 1) -> 0;
compare(1, 3) -> 1 < 3 as -1;
compare(5, 2) -> 5 > 2 as 1;
像这样比较两个字符串的最佳方法是什么?
结果看起来像这样:
compare("one", "one") -> 0;
compare("one", "three") -> -1;
compare("five", "two") -> 1;
public int compare(String a, String b) {
    return 0;
}

最佳答案

您可以使用映射对字符串及其值进行编码。这种方法的好处是它有 O(1)例如,与使用数组相反的复杂性。

Map<String, Integer> map = Map.of("one", 1, "two", 2, ...);

public int compare(String a, String b) {
      return Integer.compare(map.get(a),map.get(b));    
}
完整示例:
public class Example {

    private final static Map<String, Integer> STRING_VALUE =
            Map.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5,
                    "six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10);

    public static int compare(String a, String b) {
        return Integer.compare(STRING_VALUE.get(a),STRING_VALUE.get(b));
    }

   public static void main(String[] args) {
       System.out.println(compare("one", "one"));
       System.out.println(compare("one", "three"));
       System.out.println(compare("five", "two"));
    }
}
输出:
0
-1
1
另一种解决方案是使用 ENUM:
完整示例:
public class Example {

    enum Values {
        ONE,
        TWO,
        THREE,
        FOUR,
        FIVE,
        SIX,
        SEVEN,
        EIGHT,
        NINE,
        TEN;
    }
    public static int compare(String a, String b) {
        Values vA = Values.valueOf(a.toUpperCase());
        Values vB = Values.valueOf(b.toUpperCase());
        return Integer.compare(vA.compareTo(vB), 0);
    }

   public static void main(String[] args) {
       System.out.println(compare("one", "one"));
       System.out.println(compare("one", "three"));
       System.out.println(compare("five", "two"));
    }
}
输出:
0
-1
1

关于java - 用数字作为单词比较两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66857504/

相关文章:

java - PrintWriter——没有输出?

string - Lua:string.rep嵌套在string.gsub中?

javascript - 整数的 localeCompare

java - 测试 spring-boot @service 类

java - GWT按钮setEnabled空指针异常错误

java - 为什么java String将一些UTF-8符号视为多个字符

string - 如何确定R中字符串是否以换行符(EOL)结尾?

string - F# - 在编译时从字符串生成简单的空类型

java - 如何制作随机数模式生成器?

c# - 正则表达式搜索包含 3 个或更多数字的字符串