![](/img/trans.png)
[英]I need to compare two shapes to determine which one is bigger or smaller than the other using comparable interface
[英]How can I compare two strings in java and define which of them is smaller than the other alphabetically?
我想使用二進制搜索算法來搜索用戶在一個非常大的排序文件中輸入的字符串。 我無法將用戶輸入的字符串與位於文件中間行的字符串進行比較以繼續我的二進制搜索。
例如,如果用戶的字符串是abcda
而文件的字符串是abcza
,則很明顯用戶的字符串小於文件的字符串。 它是如何在java中實現的? 如果您能幫我提供示例代碼,那就太好了。
您可以使用
str1.compareTo(str2);
如果str1 按字典順序小於str2 ,則將返回a negative number
,如果相等則返回0
,如果str1更大則返回a positive number
。
例如,
"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
如果您想忽略大小寫,您可以使用以下命令:
String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
//-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
// strings are equal.
}
你沒聽說過String
實現的Comparable
接口嗎? 如果沒有,請嘗試使用
"abcda".compareTo("abcza")
它將為您的問題的解決方案輸出一個好的根源。
String bigString = null;
for(int i = 0; i < number; i++){
System.out.println("... ");
String sentence = sc.nextLine();
if(bigString == null || sentence.compareTo(bigString) > 0) {
bigString = sentence;
}
}
System.out.println("...: " + bigString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.