计算父字符串中子字符串出现的次数(先输入父字符串,再输入子字符串)
时间: 2023-04-29 09:01:10 浏览: 93
可以使用Python中的count()函数来计算父字符串中子字符串出现的次数。具体操作如下:
1. 首先输入父字符串,可以使用input()函数获取用户输入的字符串。
2. 然后输入子字符串,同样使用input()函数获取用户输入的字符串。
3. 使用count()函数计算子字符串在父字符串中出现的次数,代码如下:
count = 父字符串.count(子字符串)
4. 最后输出结果,代码如下:
print("子字符串在父字符串中出现的次数为:", count)
完整代码如下:
parent_str = input("请输入父字符串:")
sub_str = input("请输入子字符串:")
count = parent_str.count(sub_str)
print("子字符串在父字符串中出现的次数为:", count)
相关问题
用Java代码实现分别在控制台输入字符串和子字符串,并计算字符串中子字符串出现的次数。
好的,以下是Java代码实现:
```
import java.util.Scanner;
public class SubstringCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.nextLine();
System.out.print("请输入子字符串:");
String substr = scanner.nextLine();
int count = 0;
int index = -1;
while ((index = str.indexOf(substr, index + 1)) != -1) {
count++;
}
System.out.println("子字符串出现的次数为:" + count);
}
}
```
运行结果如下:
```
请输入字符串:abcdabcdaa
请输入子字符串:a
子字符串出现的次数为:4
```
计算字符串中子串出现的次数c语言
可以使用循环和字符串比较函数来计算字符串中子串出现的次数。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int countSubstring(char *str, char *substr) {
int count = 0;
int len = strlen(substr);
while (*str) {
if (strncmp(str, substr, len) == 0) {
count++;
}
str++;
}
return count;
}
int main() {
char str[] = "hello world";
char substr[] = "l";
int count = countSubstring(str, substr);
printf("'%s' appears %d times in '%s'\n", substr, count, str);
return 0;
}
```
这个代码会输出:
```
'l' appears 3 times in 'hello world'
```
注意这个代码只计算了出现的次数,没有考虑重叠情况。例如,如果子串是 "ll",那么在 "hello world" 中它出现的次数应该是 1,但是上面的代码会输出 2,因为 "l" 出现了两次。如果需要考虑重叠情况,可以在上面的循环中加上一个步长,例如每次移动两个字符。