java求一个字符串在另外一个字符串中出现的次数
时间: 2023-11-12 20:55:54 浏览: 45
可以使用Java中String类的indexOf()方法来实现字符串在另一个字符串中出现的次数计算。
具体代码如下:
```java
public static int countOccurrences(String mainStr, String subStr) {
int count = 0;
int lastIndex = 0;
while (lastIndex != -1) {
lastIndex = mainStr.indexOf(subStr, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += subStr.length();
}
}
return count;
}
```
其中,mainStr表示主字符串,subStr表示要查找的子字符串。该方法返回子字符串在主字符串中出现的次数。
例如,如果想要查找字符串"abc"在字符串"abcbcabcdabcd"中出现的次数,可以调用该方法:
```java
int count = countOccurrences("abcbcabcdabcd", "abc");
System.out.println(count); // 输出结果为 2
```
相关问题
java求一个字符串在另外一个字符串中出现的次数,不用api
可以通过循环遍历的方式来实现字符串在另一个字符串中出现的次数计算。
具体代码如下:
```java
public static int countOccurrences(String mainStr, String subStr) {
int count = 0;
int mainLength = mainStr.length();
int subLength = subStr.length();
for (int i = 0; i <= mainLength - subLength; i++) {
boolean isMatch = true;
for (int j = 0; j < subLength; j++) {
if (mainStr.charAt(i + j) != subStr.charAt(j)) {
isMatch = false;
break;
}
}
if (isMatch) {
count++;
}
}
return count;
}
```
其中,mainStr表示主字符串,subStr表示要查找的子字符串。该方法返回子字符串在主字符串中出现的次数。
例如,如果想要查找字符串"abc"在字符串"abcbcabcdabcd"中出现的次数,可以调用该方法:
```java
int count = countOccurrences("abcbcabcdabcd", "abc");
System.out.println(count); // 输出结果为 2
```
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
```