Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using the post-fix increment operator to add values to an array

What does count[s1.charAt(i) - 'a']++ do within the following for loop? I saw a similar question answered here but I’m still confused. I’ve never seen this syntax before and have not been able to find a lot of info about it.

String s1 = "abcd";
int[] count = new int[26];
for (int i = 0; i < len1; i++) {
  count[s1.charAt(i) - 'a']++;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Let’s examine the expression count[s1.charAt(i) - 'a']++; from the inside out.

s1.charAt(i) is the character in the ith place of the s1 string. Since letters are sequential, subtracting a from this character will convert it to an index in the count array (a is turned to 0, b is turned to 1, etc). Then, the subscript operator [] is used to reference that index in the array. And finally, ++ is used to increment the value of the array in that index.

If we put it all together – count is an array of counters for each character in the string. The loop goes over the characters in the string, and for each character increments the appropriate counter, so when its done the array will hold the counts of each character in it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading