java统计字符串str1中字符串str2出现的次数,不使用index方法
时间: 2023-06-06 11:04:33 浏览: 62
可以使用循环遍历的方式,逐个比较str1中的字符是否与str2相同,如果相同则累加出现次数。代码示例如下:
```
public static int countSubstring(String str1, String str2) {
int count = 0;
int str1Len = str1.length();
int str2Len = str2.length();
for (int i = 0; i <= str1Len - str2Len; i++) {
boolean flag = true;
for (int j = 0; j < str2Len; j++) {
if (str1.charAt(i + j) != str2.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
count++;
}
}
return count;
}
```
这样就可以统计出字符串str1中字符串str2出现的次数了。
相关问题
java统计字符串str1中字符串str2出现的次数,用数组实现
可以使用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统计指定字符串在对应字符串中出现的次数
可以使用Java中的indexOf()和substring()方法来统计指定字符串在对应字符串中出现的次数。具体实现如下:
```java
public static int countOccurrences(String str, String target) {
int count = 0;
int index = 0;
while ((index = str.indexOf(target, index)) != -1) {
count++;
index += target.length();
}
return count;
}
```
其中,str为对应字符串,target为指定字符串。使用indexOf()方法查找target在str中第一次出现的位置,若返回值不为-1,则count加1,然后继续在str中查找target,直到找不到为止。注意,每次找到一个target后,index需要加上target的长度,以便查找下一个target的位置。
调用该方法的示例代码如下:
```java
String str = "hello world, world is beautiful";
String target = "world";
int count = countOccurrences(str, target);
System.out.println(count); // 输出2
```