How can I compare two strings in java and define which of them is smaller than the other alphabetically?

前端 未结 3 1261
余生分开走
余生分开走 2020-11-30 02:27

I want to use the binary search algorithm to search the string which has been entered by the user in a very big sorted file. I can not compare the string which has been ente

3条回答
  •  醉话见心
    2020-11-30 02:58

    You can use

    str1.compareTo(str2);
    

    If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

    E.g.,

    "a".compareTo("b"); // returns a negative number, here -1
    "a".compareTo("a"); // returns  0
    "b".compareTo("a"); // returns a positive number, here 1
    "b".compareTo(null); // throws java.lang.NullPointerException
    

提交回复
热议问题