String wordOne = "Hello";
String wordTwo = "Bye";
String wordThree = "What";
假设这些是用户输入的字符串。虽然不区分大小写,但我如何仅使用if
- 语句来按字母顺序查找哪个单词/字符串?我已经开始使用.toUpperCase
尝试使用ASCII值,但我迷路了。此外,用户将能够输入相同的单词。非常感谢任何帮助。
答案 0 :(得分:-1)
使用compareToIgnoreCase()函数
int result= wordOne.compareToIgnoreCase(wordTwo);
if(result < 0){
//wordOne precedes wordTwo alphabetically
}
else if(result > 0){
//wordOne is after wordTwo alphabetically
}
else{
//they are the same
}
此处的文档: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#compareTo%28java.lang.String%29