简体   繁体   English

比较两个单词(字符串)

[英]Comparing Two Words(Strings)

What does this code mean? 这段代码是什么意思?

if( item.compareTo(root.element) < 0 ){

   }

I read that: 我读到了:

"Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument." “按字典顺序比较两个字符串。返回一个整数,指示此字符串是否大于(结果> 0),等于(结果是= 0)或小于(结果是<0)参数。”

But I don't don't get it. 但我不明白。 Can someone explain with an example please? 有人可以用一个例子解释一下吗?

Take a look at the documentation of the Comparable interface, which defines the compareTo() method in the first place. 看一下Comparable接口的文档,它首先定义了compareTo()方法。 The implementation of this interface in String follows the same conventions: String中此接口的实现遵循相同的约定:

Compares this object with the specified object for order. 将此对象与指定的对象进行比较以获得顺序。 Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object 返回负整数,零或正整数,因为此对象小于,等于或大于指定对象

This means: if the current string is less than the string received as parameter (under the lexicographical order ) return a negative integer value. 这意味着:如果当前字符串小于作为参数接收的字符串(在字典顺序下 ),则返回负整数值。 If the current string is greater than the string received as parameter, return a positive integer value. 如果当前字符串大于作为参数接收的字符串,则返回正整数值。 Otherwise, the strings are equal and 0 is returned. 否则,字符串相等,返回0

someObject . someObject compareTo ( anotherObject ) returns a negative number if someObject comes before anotherObject . 如果someObjectanotherObject之前, compareToanotherObject )返回一个负数。

Here's an example that compares String objects: 这是一个比较String对象的示例:

if ("apple".compareTo("zebra") < 0) {
    System.out.println("I will be printed");
}
else {
    System.out.println("I will NOT be printed");
}

您可以在排序代码时使用它来查看item属于root.element之前。

it checks if two Strings are equal like this. 它检查两个字符串是否相同。

a>A  would return a positive number as `a` is greater than `A`
A>a  would return a negetive number as `A` is less than `a`
a==a would return 0 as `a` is equal to `a`
a>Z  would return a positive number as 'a' is greater than 'A'
trend> zend would return a positive number as `t` is greater than 'z'   

如果word1 = item,word2 = root.element并且两者都在字典中,则word1应出现在word2之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM