java统计字符串都好分隔出现的次数
时间: 2023-04-09 15:04:11 浏览: 53
可以使用 String 类的 split() 方法将字符串按照逗号分隔成一个字符串数组,然后再统计数组中每个元素出现的次数即可。以下是示例代码:
```
String str = "a,b,c,d,e,a,b,c";
String[] arr = str.split(",");
Map<String, Integer> map = new HashMap<>();
for (String s : arr) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
System.out.println(map);
```
输出结果为:{a=2, b=2, c=2, d=1, e=1}
相关问题
java统计一个字符串中,的数量
可以使用 String 类中的 `split()` 方法和数组的 `length` 属性来统计一个字符串中某个字符的出现次数。例如,统计字符串中逗号的数量,可以使用以下代码:
```java
String str = "Java,Python,C++,JavaScript";
String[] arr = str.split(",");
int count = arr.length - 1;
System.out.println("逗号的数量为:" + count);
```
输出结果为:
```
逗号的数量为:3
```
如果要统计其他字符的数量,只需要将 `split()` 方法中的分隔符改成对应的字符即可。
字符串中出现的关键字不用统计
如果要在字符串中统计关键字出现的次数,可以先将字符串按空格或其他分隔符分割成单词,然后遍历单词列表,判断每个单词是否为关键字,如果不是则将其计数加一。具体实现可以使用如下的代码:
```java
String str = "hello world, this is a test string";
String[] words = str.split(" "); //按空格分割单词
String[] keywords = {"hello", "world", "test"}; //关键字列表
Map<String, Integer> map = new HashMap<String, Integer>(); //计数器
for (String keyword : keywords) {
map.put(keyword, 0);
}
for (String word : words) {
if (!Arrays.asList(keywords).contains(word)) { //判断单词是否为关键字
int count = map.getOrDefault(word, 0);
map.put(word, count + 1); //计数加一
}
}
System.out.println(map); //输出:{this=1, is=1, a=1, string=1}
```
这里使用了 `split()` 函数将字符串按空格分割成单词,使用了一个名为 `map` 的 HashMap 来存储每个单词的计数器,遍历单词列表时,如果单词不是关键字,则将其计数器加一。注意,这个方法只能统计单词的出现次数,无法处理字符串内部的子串匹配问题。