求一个字符串在另一个字符串中出现的次数
时间: 2023-04-19 13:00:03 浏览: 49
可以使用Python中的count()函数来求一个字符串在另一个字符串中出现的次数。
例如,假设我们要求字符串s1在字符串s2中出现的次数,可以使用以下代码:
count = s2.count(s1)
其中,count为s1在s2中出现的次数。
相关问题
一个字符串在另一个字符串中出现的次数
要计算一个字符串在另一个字符串中出现的次数,可以使用字符串的内置函数count()。该函数接受一个字符串作为参数,返回该字符串在原字符串中出现的次数。例如:
s = "hello world"
count = s.count("l")
print(count) # 输出2,因为字符串中有两个'l'
如果要计算一个字符串在另一个字符串中出现的次数,可以将原字符串和目标字符串都传入count()函数中。例如:
s = "hello world"
sub = "l"
count = s.count(sub)
print(count) # 输出3,因为字符串中有三个'l'
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
```