Java获取字符串在另一个字符串中出现的次数
时间: 2023-09-03 11:13:02 浏览: 48
您可以使用Java中的indexOf()方法和substring()方法来获取一个字符串在另一个字符串中出现的次数。以下是一个示例代码:
```java
public static int countOccurrences(String str, String subStr) {
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
```
您可以使用这个方法来计算一个字符串在另一个字符串中出现的次数。例如:
```java
String str = "hello world!";
String subStr = "l";
int count = countOccurrences(str, subStr);
System.out.println("The number of occurrences of '" + subStr + "' in '" + str + "' is: " + count);
```
输出结果为:
```
The number of occurrences of 'l' in 'hello world!' is: 3
```
相关问题
java获取一个字符串在另一个字符串中出现的次数
可以使用Java中的String类的indexOf()方法和substring()方法来实现获取一个字符串在另一个字符串中出现的次数。
具体实现步骤如下:
1. 定义两个字符串变量str1和str2,分别表示要查找的字符串和被查找的字符串。
2. 定义一个计数器变量count,用于记录str1在str2中出现的次数。
3. 使用while循环,每次在str2中查找str1的位置,如果找到了就将count加1,并将str2的起始位置设置为str1出现的位置加上str1的长度,继续查找下一个str1的位置,直到str1在str2中找不到为止。
4. 最后返回count的值,即为str1在str2中出现的次数。
示例代码如下:
```
public static int countOccurrences(String str1, String str2) {
int count = ;
int index = str2.indexOf(str1);
while (index != -1) {
count++;
index = str2.indexOf(str1, index + str1.length());
}
return count;
}
```
调用示例:
```
String str1 = "hello";
String str2 = "hello world, hello java, hello python";
int count = countOccurrences(str1, str2);
System.out.println(count); // 输出3
```
JAVA--获取目标字符串在另一个字符串中出现的次数
您可以使用Java中的String类的indexOf()方法和循环来获取目标字符串在另一个字符串中出现的次数。以下是一个示例代码:
```java
public class Main {
public static void main(String[] args) {
String str = "Hello, how are you?";
String target = "o";
int count = 0;
int index = str.indexOf(target);
while (index != -1) {
count++;
index = str.indexOf(target, index + 1);
}
System.out.println("目标字符串出现的次数为: " + count);
}
}
```
在上面的示例代码中,我们首先定义了一个字符串`str`和一个目标字符串`target`。然后,我们使用indexOf()方法查找目标字符串在`str`中的索引位置,并将其赋值给变量`index`。如果找到了目标字符串,则将计数器`count`加1,然后继续查找下一个目标字符串的索引位置,直到没有更多的目标字符串出现为止。最后,输出目标字符串出现的次数。
请注意,以上示例代码只能获取目标字符串在另一个字符串中出现的次数,而不考虑目标字符串的重叠情况。如果您需要考虑目标字符串的重叠情况,您可以使用正则表达式或其他更复杂的方法来实现。