Java完成记录一个子串在整串中出现的次数
时间: 2024-02-25 19:51:54 浏览: 73
你可以使用Java中的String类的indexOf()方法来查找子串在整串中的位置,然后使用循环来计算出现次数。以下是示例代码:
```java
public class SubstringCount {
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;
}
public static void main(String[] args) {
String str = "Java is a programming language. Java is used for web development, mobile apps, and more.";
String subStr = "Java";
int count = countSubstring(str, subStr);
System.out.println("The substring \"" + subStr + "\" appears " + count + " times in the string.");
}
}
```
输出结果:
```
The substring "Java" appears 2 times in the string.
```