Java 中的字符串比较 [英] String Comparison in Java

查看:42
本文介绍了Java 中的字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按字典序比较两个字符串"是什么意思?

What does "compare two strings lexicographically" mean?

推荐答案

根据@Bozho 和@aioobe 的回答,词典比较类似于人们可能在字典中找到的排序.

Leading from answers from @Bozho and @aioobe, lexicographic comparisons are similar to the ordering that one might find in a dictionary.

Java String 类提供了 .compareTo () 方法,以便按字典顺序比较字符串.像这样使用"apple".compareTo("banana").

The Java String class provides the .compareTo () method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana").

这个方法的返回是一个int,可以解释如下:

The return of this method is an int which can be interpreted as follows:

  • 返回<0 则调用该方法的字符串按字典顺序排在第一位(在字典中排在第一位)
  • returns == 0 那么这两个字符串在字典上是等价的
  • 返回 > 0 然后传递给 compareTo 方法的参数按字典顺序排在第一位.
  • returns < 0 then the String calling the method is lexicographically first (comes first in a dictionary)
  • returns == 0 then the two strings are lexicographically equivalent
  • returns > 0 then the parameter passed to the compareTo method is lexicographically first.

更具体地说,该方法提供了 ASCII 值的第一个非零差异.

More specifically, the method provides the first non-zero difference in ASCII values.

因此 "computer".compareTo ("comparison") 将返回 (int) 'u' - (int) 'a' (20) 的值.由于这是一个肯定的结果,参数 ("comparison") 按字典顺序排在第一位.

Thus "computer".compareTo ("comparison") will return a value of (int) 'u' - (int) 'a' (20). Since this is a positive result, the parameter ("comparison") is lexicographically first.

还有一个变体 .compareToIgnoreCase () 它将返回 0 for "a".compareToIgnoreCase ("A"); for示例.

There is also a variant .compareToIgnoreCase () which will return 0 for "a".compareToIgnoreCase ("A"); for example.

这篇关于Java 中的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆