编写一个方法(public static int count(String source, String key)),从以下内容中查找出 "String"的出现次数
时间: 2024-05-07 14:20:17 浏览: 8
可以使用 Java 中的 String 类的 indexOf() 方法来查找子字符串出现的位置,然后在源字符串中继续查找,直到找不到为止,统计出现的次数即可。下面是一个示例代码:
```java
public static int count(String source, String key) {
int count = 0;
int index = source.indexOf(key);
while (index != -1) {
count++;
index = source.indexOf(key, index + 1);
}
return count;
}
```
调用该方法时,需要传入源字符串和要查找的子字符串作为参数,例如:
```java
String source = "Java is a programming language that is used to develop applications for a variety of platforms, including Windows, Mac OS, and Linux.";
String key = "String";
int count = count(source, key);
System.out.println("The number of occurrences of \"" + key + "\" in the source string is: " + count);
```
输出结果为:
```
The number of occurrences of "String" in the source string is: 1
```