java统计字符串str1中字符串str2出现的次数,用数组实现
时间: 2023-06-06 13:04:32 浏览: 46
可以使用Java中的indexOf和循环来实现统计字符串出现次数的功能,代码如下:
```
public static int countOccurrences(String str1, String str2) {
int count = 0;
int index = str1.indexOf(str2);
while (index != -1) {
count++;
index = str1.indexOf(str2, index + 1);
}
return count;
}
```
其中,indexOf方法用于获取str2在str1中第一次出现的位置,如果返回-1表示没有找到;循环用于不断查找后续出现的位置,并累计次数。
相关问题
java统计字符串str1中字符串str2出现的次数,用数组循环遍历的方法
可以使用循环遍历的方法来统计字符串str1中字符串str2出现的次数,以下是一种实现方式:
```
public static int countOccurrences(String str1, String str2) {
int count = 0;
int str2Length = str2.length();
for (int i = 0; i <= str1.length() - str2Length; i++) {
if (str1.substring(i, i + str2Length).equals(str2)) {
count++;
}
}
return count;
}
```
该方法首先定义一个计数器count,然后以数组方式循环遍历字符串str1,每次在当前位置截取与字符串str2相同长度的子串,若该子串与str2相同,则计数器加1。最后返回计数器的值即可。
java 统计字符串中每个字符出现的次数
好的,这个问题可以回答。以下是一个简单的 Java 代码示例,用于统计字符串中每个字符出现的次数:
```
String str = "Hello World";
int[] count = new int[256];
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
count[ch]++;
}
for (int i = 0; i < 256; i++) {
if (count[i] > 0) {
System.out.println((char) i + ": " + count[i]);
}
}
```
这个代码将字符串中的每个字符转换为 ASCII 码,并在一个数组中统计每个字符出现的次数。然后,它遍历这个数组,输出每个字符出现的次数。请注意,这个代码只能统计 ASCII 字符,对于 Unicode 字符需要使用其他方法。