Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "ch - 'a' " mean? [duplicate]

Tags:

java

arrays

I was going through a piece of code which i was not able to understand. Thought of checking this with our community.

In the below code, i am not able to understand what the line count[ch-'a']++ does. or how can we write the same in java 7. What the explanation says is that we have a String s and an int array count. We iterate through the string s and count the no of occurrences of the characters in s and put the frequencies of count into the array. please help!!

String s = "test";
   int[] count = new int[26];        
   for (int i = 0; i < s.length(); i++) {
       char ch = s.charAt(i);
       count[ch-'a']++;                     
   }
like image 770
abhishek pandey Avatar asked Dec 11 '25 08:12

abhishek pandey


2 Answers

the code is trying to count the number of occurrence of each character.

and it allocates it such that

a occupies position 0
b occupies position 1
etc etc

to get position 0, you need to call 'a' - 'a'
to get position 1, you need to call 'b' - 'a'

so what is happening in "count[ch-'a']++;" is eqivalent to

int position = ch -'a'; // get position
count[position] = count [position] + 1; // increment the count in that particular position
like image 144
Angel Koh Avatar answered Dec 13 '25 22:12

Angel Koh


You are iterating over an array of ints count and incrementing the integer value at index ch-'a', which results in an integer value, e.g count['a'-'a'] == count[0] to flag that the character exists in the string.

you subtract in ch - 'a' because the integer value of alphabetic characters does not start at 0.

like image 39
Nas Dos Avatar answered Dec 13 '25 21:12

Nas Dos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!