2017-11-04 40 views
0

有人可以解释一下runner.children[c-'a'] 在下面的代码中的含义。java中的hypen( - )有什么用途

public boolean search(String word) { 
    TrieNode runner = root; 
    for(char c : word.toCharArray()) { 
     if(runner.children[c-'a'] == null) { 
      return false; 
     } else { 
      runner = runner.children[c-'a']; 
     } 
    } 
    return runner.isEndOfWord; 
} 
+1

这不是一个连字符;这是一个*减*。 – XenoRo

+0

''a''这是ascii 97,所以它是'c - 97'。 – MadProgrammer

回答

0

在这种情况下,children []可能是来自a-z的字母数量的大小。

上面的情况是,他们采用char c的ascii值,然后减去'a'的ascii代码。有效地导致在得到的炭C的索引在字母表(0指数假定)

令C = 'B'

[c-'a'] = 98 - 97 = 1 (Ascii of b - Ascii of a) 

用c = 'd'

[c-'a'] = 100 - 97 = 3 
1

这就是只是减法。你可以像字符一样减去字符。你最终得到的结果是减去它们的字符代码。 (例如)'c' - 'a'等于2,因为'a'比2小于'c'

2

每个char都有一个数值,查看the ASCII table了解更多信息。

所以假设变量c包含字符b,并减去字符从一个,你会得到你的答案。

0

这是minus符号而不是连字符。在java中char需要2个字节的空间。 char是从00000000到11111111范围内的位的表示,最高有效位被读为有符号位。你也可以通过将一个char分配给一个int变量来轻松地将它读作一个数字(因为int可以接受4个字节,所以char的两个字节可以很容易地适用)。

char charA = ''A'; // represents 65 
char charB = `B`; // represents 66 
int diff = charB - charA; // this will represent 66-65 i.e. 1 

数组的索引是positve int和因此它也可以接受像

anyTypeArray[charB - charA] //represents the 2nd element (index starts from 0 for arrays in java). 

anyTypeArray['C' - charA] // represents the 3rd element of the array 

值也很喜欢上面https://stackoverflow.com/a/47106997/504133答案,并希望增加其链接延长我的答案。

1

-是减法运算符。

§15.18.2 The type of each of the operands of the binary - operator must be a type that is convertible to a primitive numeric type

§5.6.2 Widening primitive conversion is applied to convert either or both operands … both operands are converted to type int. Binary numeric promotion is performed on the operands of certain operators: … addition and subtraction operators for numeric types + and - …

换言之,既c'a'char类型(UTF-16代码单元,其具有范围为Character.MIN_VALUECharacter.MAX_VALUE)的。由于减法,它们被扩大到输入int,减去,导致int类型的值。

想想数字上的字符。减法是指从一个角色到另一角色的距离。通过对'a'的恒定参考,'a','b',... 'z'的距离是0,1,... 25。这仅在UTF-16号码行的某些短段上才有意义。

数组是基于0的,所以像这样移动比例尺允许使用字符来索引数组而不用大的使用部分,其元素对应于未使用的字符。

(注:有些人说ASCII,因为他们认为这是比较容易理解的方式更简单,做错事要学习正确的事)