统计子字符串substr在字符串str中出现的次数
时间: 2023-11-15 19:04:32 浏览: 121
可以使用字符串的find方法来实现统计子字符串在字符串中出现的次数。具体的做法是,使用循环和find方法依次查找子字符串在字符串中的位置,每次查找到一个位置就将查找的起点更新为该位置的下一个位置,直到查找不到为止。代码如下:
```python
def count_substr(str, substr):
count = 0
start = 0
while True:
pos = str.find(substr, start)
if pos == -1:
break
count += 1
start = pos + 1
return count
```
这个函数接受两个字符串参数,分别是要查找的原字符串和要统计的子字符串。函数返回子字符串在原字符串中出现的次数。例如:
```python
str = "hello world, world is beautiful"
substr = "world"
count = count_substr(str, substr)
print(count)
```
输出结果为:
```
2
```
相关问题
用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!'
```
编写一个函数totsubstrnum(char *str,char *substr),它的功能是统计子字符串substr在字符串str中出现的次数
好的,下面是函数的实现:
```c
int totsubstrnum(char *str, char *substr) {
int count = 0;
int str_len = strlen(str);
int substr_len = strlen(substr);
for (int i = 0; i <= str_len - substr_len; i++) {
if (strncmp(str + i, substr, substr_len) == 0) {
count++;
}
}
return count;
}
```
函数的参数是两个字符串指针 `str` 和 `substr`,返回值是子字符串 `substr` 在字符串 `str` 中出现的次数。
函数的实现比较简单,就是遍历字符串 `str` 的所有可能的子字符串,如果找到了一个与 `substr` 相同的子字符串,就将计数器 `count` 加 1。最后返回计数器的值即可。
注意,这里使用了 C 语言的库函数 `strncmp` 来比较两个字符串的前缀是否相同。`strncmp` 函数的第一个参数是一个指向字符串的指针,第二个参数是另一个指向字符串的指针,第三个参数是要比较的字符数。如果前缀相同,就返回 0,否则返回一个非零值。
希望能够帮助到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)