Java例子 abcacdaac a 出现的次数
时间: 2024-01-16 15:04:24 浏览: 25
以下是一个 Java 代码示例,用于计算给定字符串中特定子字符串出现的次数:
```
public static int countOccurrences(String str, String subStr) {
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
// 示例用法
String str = "abcacdaac";
String subStr = "a";
int count = countOccurrences(str, subStr);
System.out.println("字符串 " + str + " 中出现 " + subStr + " 的次数为 " + count);
```
该代码使用 `indexOf()` 方法在字符串中查找子字符串的出现位置,并使用循环计算出现次数。在每次找到子字符串后,将计数器加 1 并更新查找的起始位置。
在以上示例中,将字符串 "abcacdaac" 和子字符串 "a" 传递给 `countOccurrences()` 方法,它将返回 3,即子字符串 "a" 出现的次数。
相关问题
java统计单个字符出现次数
可以使用 HashMap 来存储每个字符出现的次数。具体思路如下:
1. 遍历字符串中的每个字符
2. 判断该字符是否已经在 HashMap 中出现过
- 如果已经出现过,则将对应 value 值加 1
- 如果没有出现过,则将该字符作为 key,value 值设为 1,加入到 HashMap 中
3. 遍历 HashMap,输出每个字符及其出现次数
下面是示例代码:
```java
public static void countChars(String str) {
// 创建 HashMap
HashMap<Character, Integer> map = new HashMap<>();
// 遍历字符串中的每个字符
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// 判断该字符是否已经在 HashMap 中出现过
if (map.containsKey(c)) {
// 如果已经出现过,则将对应 value 值加 1
int count = map.get(c);
map.put(c, count + 1);
} else {
// 如果没有出现过,则将该字符作为 key,value 值设为 1,加入到 HashMap 中
map.put(c, 1);
}
}
// 遍历 HashMap,输出每个字符及其出现次数
for (Character c : map.keySet()) {
System.out.println(c + ": " + map.get(c));
}
}
```
调用该方法:
```java
String str = "hello world";
countChars(str);
```
输出结果:
```
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
```
java统计单词出现的次数
要统计Java中单词出现的次数,可以使用HashMap数据结构来记录每个单词出现的次数。具体步骤如下:
1. 将字符串转换为小写字母,方便统计单词出现的次数。
2. 使用正则表达式将字符串分割成单词数组。
3. 遍历单词数组,使用HashMap记录每个单词出现的次数。
4. 输出HashMap中每个单词出现的次数。
下面是一段示例代码:
```
public static void countWords(String text) {
// 将字符串转换为小写字母
text = text.toLowerCase();
// 使用正则表达式分割字符串成单词数组
String[] words = text.split("[^a-zA-Z]+");
// 使用HashMap记录每个单词出现的次数
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
if (word.length() > 0) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
}
// 输出每个单词出现的次数
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
```
可以调用该方法并传入需要统计的字符串,如下所示:
```
String text = "Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible.";
countWords(text);
```
输出结果如下:
```
java: 1
is: 1
a: 1
general: 1
purpose: 1
programming: 1
language: 1
that: 1
class: 1
based: 1
object: 1
oriented: 1
and: 1
designed: 1
to: 1
have: 1
as: 1
few: 1
implementation: 1
dependencies: 1
possible: 1
```