Java中获取一个字符串在另一个字符串出现的次数
时间: 2025-01-06 16:52:30 浏览: 4
在Java中,要获取一个字符串在另一个字符串中出现的次数,可以使用多种方法。以下是几种常见的方法:
1. 使用`indexOf()`方法:
```java
public class StringOccurrences {
public static int countOccurrences(String mainString, String subString) {
int count = 0;
int index = 0;
while ((index = mainString.indexOf(subString, index)) != -1) {
count++;
index += subString.length();
}
return count;
}
public static void main(String[] args) {
String mainString = "Hello, this is a test. This test is simple.";
String subString = "test";
int occurrences = countOccurrences(mainString, subString);
System.out.println("Occurrences of \"" + subString + "\": " + occurrences);
}
}
```
2. 使用`split()`方法:
```java
public class StringOccurrences {
public static int countOccurrences(String mainString, String subString) {
if (subString.isEmpty()) {
return 0;
}
String[] parts = mainString.split(Pattern.quote(subString));
return parts.length - 1;
}
public static void main(String[] args) {
String mainString = "Hello, this is a test. This test is simple.";
String subString = "test";
int occurrences = countOccurrences(mainString, subString);
System.out.println("Occurrences of \"" + subString + "\": " + occurrences);
}
}
```
3. 使用正则表达式:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringOccurrences {
public static int countOccurrences(String mainString, String subString) {
Pattern pattern = Pattern.compile(Pattern.quote(subString));
Matcher matcher = pattern.matcher(mainString);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
public static void main(String[] args) {
String mainString = "Hello, this is a test. This test is simple.";
String subString = "test";
int occurrences = countOccurrences(mainString, subString);
System.out.println("Occurrences of \"" + subString + "\": " + occurrences);
}
}
```
这些方法都可以用来计算一个字符串在另一个字符串中出现的次数。你可以根据具体需求选择合适的方法。
阅读全文