java实现一个方法,接受一个字符串和一个子串中出现的次数并返回结果
时间: 2024-04-30 21:22:29 浏览: 14
以下是Java代码实现:
```java
public static int countSubstring(String str, String subStr) {
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
```
该方法接受两个参数,分别是字符串和子串。它使用 indexOf() 方法来查找子串在字符串中出现的位置,每找到一次就增加计数器,并继续查找下一个位置,直到找不到为止。最终,该方法返回计数器的值,即子串在字符串中出现的次数。
相关问题
Java编写一个方法,计算一个字符串中某一子串出现的次数并返回
可以使用Java中的String类的indexOf()方法来查找子串出现的位置,然后使用循环来计算出现的次数。以下是示例代码:
public static int countSubstring(String str, String subStr) {
int count = 0;
int index = str.indexOf(subStr);
while (index != -1) {
count++;
index = str.indexOf(subStr, index + 1);
}
return count;
}
调用该方法时,传入要查找的字符串和子串即可:
String str = "hello world, world is beautiful!";
String subStr = "world";
int count = countSubstring(str, subStr);
System.out.println("子串出现的次数为:" + count);
输出结果为:
子串出现的次数为:2
Java编写一个方法,计算一个字符串中某一子串出现的次数并返回。
可以使用 Java 的 String 类的 indexOf() 方法来查找子串出现的位置,然后循环查找并计数即可。代码如下:
public static int countSubstring(String str, String subStr) {
int count = 0;
int index = str.indexOf(subStr);
while (index != -1) {
count++;
index = str.indexOf(subStr, index + 1);
}
return count;
}
其中,str 是原始字符串,subStr 是要查找的子串。该方法返回子串在原始字符串中出现的次数。