【问题标题】:Hierarchy of characters in compareTo() function of javajava的compareTo()函数中的字符层次结构
【发布时间】:2020-04-03 06:48:56
【问题描述】:

我是新来的,所以我不太了解是否有针对不同问题等的任何部分。非常抱歉,提前。

所以,我的问题是,谁能告诉我 java 的 compareTo() 函数中字符的层次结构或更确切地说是字符串的层次结构。在这段代码中...

String s1 = "HELLO";
String s2 = "hello";
int c;
c = s1.compareTo(s2);
System.out.println(c);

在这里,输出是-32,这意味着'H'小于'h'。所以我想知道字符从最高值到最低值排列的列表。提前致谢。

【问题讨论】:

  • 问题的类别是标签,你做对了。
  • 它是用javadoc 编写的String.compareTo() 方法。引用:“比较基于字符串中每个字符的 Unicode 值”。

标签: java string compare hierarchy


【解决方案1】:

compareTo 方法的工作原理如下:-

Syntax : 
int compareTo(String anotherString)
Parameters : 
anotherString :  the String to be compared.
Return Value :  
The value 0 if the argument is a string lexicographically equal to this string;
a value less than 0 if the argument is a string lexicographically greater than this string; 
and a value greater than 0 if the argument is a string lexicographically less than this string.

在你的情况下,你正在尝试比较

字符串 s1 = "你好"; // H 的 ASCII 值为 72

字符串 s2 = "你好"; // h 的 ASCII 值是 104

它会逐个字符比较,直到它们不同的字符,然后返回两个 ASCII 值的减法,否则返回 0。

在您的情况下,H 和 h 的值不同,它返回 ASCII(H)-ASCII(h)=-32 的减法。

您可以在https://theasciicode.com.ar/ascii-printable-characters/capital-letter-z-uppercase-ascii-code-90.html处引用字符的不同ASCII值

【讨论】:

    【解决方案2】:

    compareTo() 方法使用 Unicode 值来比较字符串。完整列表可在此处找到:https://en.wikipedia.org/wiki/List_of_Unicode_characters

    在谷歌图像上查找 Unicode 值以获取图表可能很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多