【发布时间】:2020-07-04 16:30:16
【问题描述】:
我是 Java 新手,我尝试使用 compareTo() 按字母顺序对电子邮件地址进行排序,但结果并不如我所愿。我把我的问题写在代码里,你能指教吗?
public class SortTest {
public static void main(String[] args) {
String text1= "customer1@example.com";
String text2 = "customer10@example.com";
System.out.println(text1.compareTo(text2)); //Result is 16. Why? I expect a negative number as result.
String text3= "customer1";
String text4 = "customer10";
System.out.println(text3.compareTo(text4)); //result is -1 which is correct.
}
}
更新:
我想用上面的text1和text2升序排序,按顺序的预期结果是"customer1@example.com",然后是"customer10@example.com"。你能建议如何实现它吗?
【问题讨论】:
-
'@'是64,'0'是48。所以'@' > '0',意思是"customer1@".compareTo("customer10") > 0。有什么意外? -
谢谢!现在我明白为什么它返回 16。我想用上面的 text1 和 text2 升序排序,按顺序的预期结果是 customer1@example.com,然后是 customer10@example.com。你能建议如何实现它吗?
-
那么看来你需要比较文本直到
@,类似于text1.substring(0, text1.indexOf("@")).compareTo(text2.substring(0, text2.indexOf("@")))
标签: java regex string algorithm sorting