gpt4 book ai didi

java - java字符串中equals和compareto方法的区别

转载 作者:行者123 更新时间:2023-12-02 00:50:06 25 4
gpt4 key购买 nike

实际上,我正在比较两个字符串,当我使用 equals 方法时,它们返回 true。而当我使用compareTo方法时它返回22。

我还想知道这两个字符串在什么地方不同。使用java我如何找到这个?

提前致谢。

最佳答案

根据compareTo()的文档

[...] If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

 this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:

 this.length()-anotherString.length()

因此,22并不是两个字符串中不同字符的位置,而是第一个不同字符之间的距离。

关于你的第二个问题,我相信对两个字符串中的字符进行简单的迭代将允许你轻松地找出它们不同的第一个字符位置

关于java - java字符串中equals和compareto方法的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3582060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com