如何将字符数存储在 char 数组中。基本上想在数组上使用增量运算符
How count of characters getting stored in char array. Basically wanted to the working of increment operator on the array
public static void getCharCountArray(String str)
{
for (int i = 0; i < str.length(); i++)
{
count[str.charAt(i)]++;
}
}
count数组如何得到字符的计数。增量运算符的工作原理?
count
是整数的索引数组。
该数组的每个索引都是一个字符。
char 数据类型是单个 16 位 Unicode 字符。它的最小值为 '\u0000'(或 0),最大值为 '\uffff'(或 65,535,含)。
在您的循环中,str.charAt(i)
return 当前迭代的字符串 str 的字符。
您使用以下表达式获取字符串当前字符的先前计数:
count[str.charAt(i)]
然后您使用 ++
运算符增加此值。
我们可以这样重写您的代码:
for (int i = 0; i < str.length(); i++)
{
char currentChar = str.charAt(i);
int previousCharCount = count[currentChar];
int currentCharCount = previousCharCount + 1;
count[currentChar] = currentCharCount;
}
您的台词:count[str.charAt(i)]++;
做同样的事情,但方式更简单、更易读。
++
运算符,不对数组进行增量操作(无意义),而是对位置char
.
处的整数值进行增量操作
public static void getCharCountArray(String str)
{
for (int i = 0; i < str.length(); i++)
{
count[str.charAt(i)]++;
}
}
count数组如何得到字符的计数。增量运算符的工作原理?
count
是整数的索引数组。
该数组的每个索引都是一个字符。
char 数据类型是单个 16 位 Unicode 字符。它的最小值为 '\u0000'(或 0),最大值为 '\uffff'(或 65,535,含)。
在您的循环中,str.charAt(i)
return 当前迭代的字符串 str 的字符。
您使用以下表达式获取字符串当前字符的先前计数:
count[str.charAt(i)]
然后您使用 ++
运算符增加此值。
我们可以这样重写您的代码:
for (int i = 0; i < str.length(); i++)
{
char currentChar = str.charAt(i);
int previousCharCount = count[currentChar];
int currentCharCount = previousCharCount + 1;
count[currentChar] = currentCharCount;
}
您的台词:count[str.charAt(i)]++;
做同样的事情,但方式更简单、更易读。
++
运算符,不对数组进行增量操作(无意义),而是对位置char
.