2017-11-04 38 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,因爲他們認爲這是比較容易理解的方式更簡單,做錯事要學習正確的事)