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

标签 java string

实际上,我正在比较两个字符串,当我使用 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/

相关文章:

javascript - 使用 .split() 将字符串转换为数组(需要改进)

c - 插入节点并按字母顺序排列

Java继承

java - 在 Java 中加载 32 位或 64 位 JNI 库

c++ - 快速排序字符串数组帮助 C++

java - 简单的字符串比较不起作用

php - 从字符串中提取单个(无符号)整数

java - 如何让整个单词使用子字符串?

java - 使用 JWT (java-jwt) 验证签名

java - Maven Eclipse 调试 "JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)"