输入字符串a,b,求b在a中出现的次数
时间: 2024-06-04 16:12:53 浏览: 12
答案:你要统计 b 在 a 中出现的次数,可以使用 Python 中的 count() 方法,代码如下:
a = input("请输入字符串a:")
b = input("请输入字符串b:")
count = a.count(b)
print("{} 在 {} 中出现了 {} 次".format(b, a, count))
相关问题
从键盘输入字符串A和字符串B,统计字符串B出现在字符串A中的次数,
为了统计字符串B在字符串A中出现的次数,我们可以使用字符串的indexOf()方法来查找字符串B在字符串A中的位置,如果找到了,就将计数器加1,然后从上一次找到的位置的下一个位置开始继续查找,直到找不到为止。具体步骤如下:
1. 从键盘输入字符串A和字符串B。
2. 定义一个计数器count,初始化为0。
3. 使用indexOf()方法查找字符串B在字符串A中的位置,如果找到了,就将计数器加1。
4. 将查找的起始位置设置为上一次找到的位置的下一个位置,继续查找,直到找不到为止。
5. 输出字符串B在字符串A中出现的次数。
代码示例:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串A:");
String strA = scanner.nextLine();
System.out.print("请输入字符串B:");
String strB = scanner.nextLine();
int count = 0;
int index = strA.indexOf(strB);
while (index != -1) {
count++;
index = strA.indexOf(strB, index + 1);
}
System.out.println("字符串B在字符串A中出现的次数为:" + count);
}
}
```
从键盘输入字符串A和字符串B,统计字符串B出现在字符串B的次数,并把字符串A倒序输出,
这里提供一个从键盘输入字符串A和字符串B,统计字符串B出现在字符串A的次数的Python代码:
```
while True:
A = input("请输入字符串A:")
if A.isalnum() == False:
print("字符串中的字符只能是数字或字母,请重新输入!\n")
continue
else:
break
while True:
B = input("请输入字符串B:")
if B.isalnum() == False:
print("字符串中的字符只能是数字或字母,请重新输入!\n")
continue
else:
break
count = 0
for i in range(len(A)-len(B)+1):
if A[i:i+len(B)] == B:
count += 1
print("字符串B在字符串A中出现的次数是%d次" % count)
print("字符串A倒序输出为:%s" % A[::-1])
```
解释一下代码:首先通过while循环从键盘输入字符串A和字符串B,然后使用for循环遍历字符串A,判断是否有与字符串B相同的子串,如果有则计数器加1。最后输出字符串B在字符串A中出现的次数和字符串A的倒序输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![png](https://img-home.csdnimg.cn/images/20210720083516.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)