3

What does the “- 97” mean in the following code?

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

we created an array of 26 LinkedList to simulate a dictionary. each list contains all words starting with “a”, “b”, “c”, …. “z”. the code was given by instructor.

Here is the attached note:

To search a word in a specific MyLinkedList

Assume that the word you want to search is in a String type variable called wordstr.

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

would allow you to jump to the correct linked list, and the contains will return true/false depending if the word is in the list or not.

I just don’t understand why the “-97”

Community
  • 1
  • 1
greg
  • 338
  • 7
  • 17

1 Answers1

9

97 is the numeric value of the character 'a', so if you subtract 97 from a character between 'a' and 'z', you are mapping that character to an index of your array between 0 and 25.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thank you ... So, the expression [(int)wordstr.charAt(0) – 97] evaluates to the index of dictionary array? And, if the wordstr is “apple”, then [(int)wordstr.charAt(0) – 97] means (character at index 0 of wordstr “apple”) ? Ie, 97 - 97 = 0, which is the index. Then “boy” is index = (98-97) = 1 ? – greg Apr 12 '15 at 06:49
  • 2
    @greg Because of confusion you just had we call such numbers "magic" and generally [we should avoid them](http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad). Instead of `(int) word.charAt(0) -97` part could be written as `(int)wordstr.charAt(0) - 'a'` which will probably be more readable (if you know that you can subtract characters to get integer representing their *distance* in Unicode Table). – Pshemo Apr 12 '15 at 09:08
  • Very insightful. Thank you both. And yes, (int)wordstr.charAt(0) - 'a' makes more sense. – greg Apr 12 '15 at 15:11