“按字典顺序比较两个字符串”是什么意思?
发布于 2010-11-01 03:14:32
String.compareTo(..)
方法执行字典序比较。按字典顺序按字母顺序排列==。
发布于 2010-11-01 03:14:33
按顺序比较位置相同的字母..更像是如何在字典中排序单词
发布于 2021-09-23 09:47:48
您可能还会遇到一项任务,其中您必须“手动”实现词典编目比较,而不是使用默认的compareTo()
方法。
下面的简单算法基于比较后续位置的字符的Unicode值。
@Override
public int compareTo(Person otherPerson) {
// Getters, constructor, variables ...
int result = 0;
for (int i = 0; i < getName().length() && i < otherPerson.getName().length(); i++) {
if (getName().charAt(i) > otherPerson.getName().charAt(i)) {
result = 1;
break;
} else if (getName().charAt(i) < otherPerson.getName().charAt(i)) {
result = -1;
break;
}
}
}
return result;
}
}
https://stackoverflow.com/questions/4064633
复制相似问题