用java统计一个字符串中每个字符出现的次数
时间: 2023-11-12 13:12:39 浏览: 32
可以使用HashMap来统计字符串中每个字符出现的次数。具体实现如下:
```java
public static void countCharacters(String str) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
int count = map.get(c);
map.put(c, count + 1);
} else {
map.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
```
调用该方法,并传入需要统计的字符串即可:
```java
String str = "hello world";
countCharacters(str);
```
输出结果为:
```
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
```
相关问题
java统计一个字符串中每个字符出现的次数
可以使用一个 HashMap 来统计每个字符出现的次数。遍历字符串,对于每个字符,如果它已经在 HashMap 中,则将其对应的计数器加一;否则,将其添加到 HashMap 中,并将计数器初始化为 1。最后遍历 HashMap,输出每个字符及其出现的次数。
以下是 Java 代码示例:
```java
import java.util.*;
public class CharacterCount {
public static void main(String[] args) {
String str = "hello world";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
输出结果为:
```
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
```
用Java写统计一个字符串中每个字符的出现次数并排序
您好,我可以回答这个问题。以下是用 Java 统计一个字符串中每个字符的出现次数并排序的代码:
```java
import java.util.*;
public class CharCount {
public static void main(String[] args) {
String str = "hello world";
Map<Character, Integer> map = new HashMap<>();
for (int i = ; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for (Map.Entry<Character, Integer> entry : list) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
这段代码会输出每个字符及其出现次数,按照出现次数从大到小排序。