Java什么方式可以求字符串中不同字母的数量,除了set集合还有什么方式
时间: 2024-03-04 16:49:29 浏览: 25
除了Set集合之外,Java中还可以使用数组的方式来求字符串中不同字母的数量。
具体实现方式如下:
1. 创建一个长度为26的数组,用于存储每个字母出现的次数。
2. 遍历字符串中的每个字符,根据字母的ASCII码值计算出它在数组中对应的下标,将对应下标的元素值加1。
3. 遍历数组,统计值不为0的元素个数,即为字符串中不同字母的数量。
以下是示例代码:
```java
public static int countDistinctLetters(String str) {
int[] letterCount = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
letterCount[c - 'a']++;
} else if (c >= 'A' && c <= 'Z') {
letterCount[c - 'A']++;
}
}
int count = 0;
for (int i = 0; i < letterCount.length; i++) {
if (letterCount[i] > 0) {
count++;
}
}
return count;
}
```
调用该方法并传入一个字符串,即可返回该字符串中不同字母的数量。