【问题标题】:What does the “- 97” mean in the following code?以下代码中的“- 97”是什么意思?
【发布时间】:2015-06-17 15:44:44
【问题描述】:

下面代码中的“-97”是什么意思?

if (dictionary[(int) word.charAt(0) -97 ].contains(word))

我们创建了一个包含 26 个 LinkedList 的数组来模拟字典。 每个列表包含所有以“a”、“b”、“c”、...开头的单词。 “z”。 代码是导师给的。

附注如下:

在特定的 MyLinkedList 中搜索单词

假设您要搜索的单词在一个名为 wordstr 的字符串类型变量中。

dictionary [(int)wordstr.charAt(0) - 97].contains(wordstr) ; 

将允许您跳转到正确的链接列表,并且包含将根据单词是否在列表中返回真/假。

我只是不明白为什么“-97”

【问题讨论】:

    标签: java string search linked-list contains


    【解决方案1】:

    97 是字符“a”的数值,因此如果从“a”和“z”之间的字符中减去 97,则将该字符映射到 0 到 25 之间的数组索引。

    【讨论】:

    • 谢谢... 那么,表达式 [(int)wordstr.charAt(0) – 97] 的计算结果是字典数组的索引?而且,如果 wordstr 是“apple”,那么 [(int)wordstr.charAt(0) – 97] 表示(wordstr “apple” 的索引 0 处的字符)?即,97 - 97 = 0,即索引。那么“男孩”就是 index = (98-97) = 1 ?
    • @greg 由于混淆,您刚刚让我们称这些数字为“魔术”,通常为we should avoid them。而不是(int) word.charAt(0) -97,部分可以写成(int)wordstr.charAt(0) - 'a',这可能更具可读性(如果您知道可以减去字符以获得表示它们在Unicode表中的距离的整数)。
    • 非常有见地。谢谢你们俩。是的,(int)wordstr.charAt(0) - 'a' 更有意义。
    猜你喜欢
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多