Java编写程序,查找一个子串在整串中出现的次数。
时间: 2023-06-12 17:02:26 浏览: 99
可以使用Java的String类的indexOf()方法来查找子串在整串中第一次出现的位置,然后通过while循环不断查找后续出现的位置直到整个字符串中没有该子串,最终得到子串在整串中出现的次数。具体代码如下:
```
public static int countSubString(String str, String subStr) {
if (str == null || subStr == null || str.length() < subStr.length()) {
return 0;
}
int count = 0;
int index = str.indexOf(subStr);
while (index != -1) {
count++;
index = str.indexOf(subStr, index + subStr.length());
}
return count;
}
```
调用该方法时,需要传入需要进行查找的字符串和子串,例如:
```
String str = "Java is a popular programming language. Java is used for developing a wide range of applications, from mobile devices to enterprise servers.";
String subStr = "Java";
int count = countSubString(str, subStr);
System.out.println("子串\"" + subStr + "\"在字符串\"" + str + "\"中出现的次数为:" + count);
输出结果为:
子串"Java"在字符串"Java is a popular programming language. Java is used for developing a wide range of applications, from mobile devices to enterprise servers."中出现的次数为:2
```
阅读全文