java统计字符串str1中字符串str2出现的次数,用数组实现
时间: 2023-06-06 12:04:32 浏览: 77
可以使用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代码写,创建一个长度是100的字符串数组 使用长度是2的随机字符填充该字符串数组 统计这个字符串数组里重复的字符串有多少种
好的,我会记住你的要求。现在回答你的问题:
您可以使用以下Java代码创建长度为100的字符串数组并使用2个随机字符进行填充:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
String[] arr = new String[100];
Random rnd = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = "" + (char) (rnd.nextInt(26) + 'a') + (char) (rnd.nextInt(26) + 'a');
}
}
}
```
要统计重复的字符串数量,您可以使用Map来存储每个字符串出现的次数,然后计算出现次数大于1的字符串数量。下面是示例代码:
```java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String[] arr = new String[100];
fillRandom(arr);
Map<String, Integer> freqMap = new HashMap<>();
for (String str : arr) {
freqMap.put(str, freqMap.getOrDefault(str, 0) + 1);
}
int count = 0;
for (int freq : freqMap.values()) {
if (freq > 1) {
count++;
}
}
System.out.println("重复的字符串数量为:" + count);
}
private static void fillRandom(String[] arr) {
Random rnd = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = "" + (char) (rnd.nextInt(26) + 'a') + (char) (rnd.nextInt(26) + 'a');
}
}
}
```
希望这能够回答您的问题。如果您有其他问题,请随时问我。
阅读全文
相关推荐













