java统计字符串str1中字符串str2出现的次数,用数组循环遍历的方法
时间: 2023-06-06 16:04:21 浏览: 53
可以使用循环遍历的方法来统计字符串str1中字符串str2出现的次数,以下是一种实现方式:
```
public static int countOccurrences(String str1, String str2) {
int count = 0;
int str2Length = str2.length();
for (int i = 0; i <= str1.length() - str2Length; i++) {
if (str1.substring(i, i + str2Length).equals(str2)) {
count++;
}
}
return count;
}
```
该方法首先定义一个计数器count,然后以数组方式循环遍历字符串str1,每次在当前位置截取与字符串str2相同长度的子串,若该子串与str2相同,则计数器加1。最后返回计数器的值即可。
相关问题
java统计字符串str1中字符串str2出现的次数,不使用index方法
可以使用循环遍历的方式,逐个比较str1中的字符是否与str2相同,如果相同则累加出现次数。代码示例如下:
```
public static int countSubstring(String str1, String str2) {
int count = 0;
int str1Len = str1.length();
int str2Len = str2.length();
for (int i = 0; i <= str1Len - str2Len; i++) {
boolean flag = true;
for (int j = 0; j < str2Len; j++) {
if (str1.charAt(i + j) != str2.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
count++;
}
}
return count;
}
```
这样就可以统计出字符串str1中字符串str2出现的次数了。
用c语言循环统计子字符串substr在字符串str中出现的次数
可以使用两层循环遍历字符串str,逐个匹配判断是否为子字符串substr,并在匹配成功时计数器加1。具体代码如下:
```c
#include <stdio.h>
#include <string.h>
int count_substr(const char* str, const char* substr) {
int count = 0;
int len_str = strlen(str);
int len_substr = strlen(substr);
for (int i = 0; i < len_str - len_substr + 1; i++) { // 遍历字符串str
int j;
for (j = 0; j < len_substr; j++) { // 遍历子字符串substr
if (str[i+j] != substr[j])
break;
}
if (j == len_substr) // 匹配成功
count++;
}
return count;
}
int main() {
char str[] = "hello world, hello everyone!";
char substr[] = "hello";
int count = count_substr(str, substr);
printf("'%s' appears %d times in '%s'\n", substr, count, str);
return 0;
}
```
输出:
```
'hello' appears 2 times in 'hello world, hello everyone!'
```