关于代码行的问题

huangapple go评论65阅读模式
英文:

Question in regards to a line of the code

问题

在下面的代码片段中,我有一个问题,给定的声明数组的类型是整数。你能解释一下在map[s.charAt(i)]++这一行发生了什么吗?我在理解这个语句时遇到了困难,因为在初始化期间数组的类型是整数,但输入却是字符类型。

public int firstUniqChar(String s) 
{ 
    int[] map = new int[128]; 
    for(int i=0; i<s.length(); i++)
        map[s.charAt(i)]++; 
    for(int i=0; i<s.length(); i++) 
        if(map[s.charAt(i)] == 1) 
            return i; 
    return -1;
}
英文:

In the below code snipped I have a question, the given declared array is of type integer.Can you please explain on what is happening at the line map[s.charAt(i)]++. I am having trouble understanding the statement here as the array is of type integer during initialization, but character type are being given as input.

public int firstUniqChar(String s) 
{ 
int[] map = new int[128]; 
for(int i=0;i&lt;s.length();i++)
 map[s.charAt(i)]++; 
for(int i=0;i&lt;s.length();i++) 
if(map[s.charAt(i)] == 1) 
return i; 
return -1;
 }

答案1

得分: 1

在Java中,假设您有一个int i = 0的变量声明,i++是一个语法糖,用于将1添加到变量值,即i = i + 1

在您的情况下,您正在将1添加到由s.charAt(i)索引的map数组位置。

假设s是一个String对象,s.charAt(i)返回位置为i(从0开始计数)的char。当Java将char读取为int(用于索引map数组)时,它使用该char的ASCII码。

因此,map[s.charAt(i)]++的作用是将1添加到由字符的ASCII码索引的map数组。

英文:

In java, supposing you have a int i = 0 variable declaration, the i++ is a syntax suggar to sum 1 to variable value, i.e. i = i + 1.
In your case you are summing 1 to an map array position, indexed by s.charAt(i).

Supposing s is a String object, s.charAt(i) returns the char at the i position (0-indexed). When the Java reads the char as a int (to index the map array), is uses the ASCII code of that char.

So, what map[s.charAt(i)]++ does is to sum 1 to the map array indexed by the charactere's ASCII code.

huangapple
  • 本文由 发表于 2020年9月26日 11:39:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64073631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定