请解释一下这行代码 a[s1.charAt(i) - 'a']++;

我正在做一个 java 程序,但不明白这行代码是如何工作的。

for (int i = 0; i < s1.length(); i++)
    a[s1.charAt(i) - 'a']++;


慕婉清6462132
浏览 533回答 2
2回答

蝴蝶不菲

s1.charAt(i)返回s1&nbsp;i的第 ' 个字符。假设这个字符串只包含小写字母(即'a'到'z'),将字符'a'映射到索引0,'b'映射到索引1,依此类推('z'映射到索引25) .Strings1.charAt(i)-'a'a[s1.charAt(i)-'a']++;递增与字符对应的计数器s1.charAt(i)。因此,这个循环计算每个字母在String&nbsp;s1.最后,a[0]将包含'a'a[1]的数量,'b'的数量等等。

慕运维8079593

for(int i=0;i<s1.length();i++)//This line represents loop from 0 to length of s1-1&nbsp; &nbsp; &nbsp; &nbsp; a[s1.charAt(i)-'a']++;//s1.chatAt(i) returns the character presents at ith index.//s1.chatAt(i)-'a' returns (ASCII value of s1.charAt(i) - ASCII value of 'a')&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java