获取一个字符串在另一个字符串中出现的次数
时间: 2023-03-16 14:48:33 浏览: 80
可以使用Python中的str.count()函数来获取一个字符串在另一个字符串中出现的次数。
例如:
```
text = "hello, world! hello, world!"
substring = "hello"
count = text.count(substring)
print(count) # 2
```
这样就能输出 "hello" 在 "hello, world! hello, world!" 出现的次数为 2
相关问题
Java获取字符串在另一个字符串中出现的次数
您可以使用Java中的indexOf()方法和substring()方法来获取一个字符串在另一个字符串中出现的次数。以下是一个示例代码:
```java
public static int countOccurrences(String str, String subStr) {
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
```
您可以使用这个方法来计算一个字符串在另一个字符串中出现的次数。例如:
```java
String str = "hello world!";
String subStr = "l";
int count = countOccurrences(str, subStr);
System.out.println("The number of occurrences of '" + subStr + "' in '" + str + "' is: " + count);
```
输出结果为:
```
The number of occurrences of 'l' in 'hello world!' is: 3
```
获取一个字符串在另一个字符串出现的次数
可以使用Python中的count()函数来获取一个字符串在另一个字符串出现的次数。例如:
```
str1 = "hello world"
str2 = "o"
count = str1.count(str2)
print(count)
```
输出结果为:2
其中,str1是要查找的字符串,str2是要查找的子字符串,count()函数返回子字符串在字符串中出现的次数。