统计一个字符串里面另一个字符串出现的次数
时间: 2023-04-26 10:03:15 浏览: 60
可以使用Python中的count()函数来统计一个字符串里面另一个字符串出现的次数。例如:
```python
s = "hello world, hello python, hello AI"
count = s.count("hello")
print(count) # 输出3
```
以上代码中,我们定义了一个字符串s,然后使用count()函数统计了字符串"hello"在s中出现的次数,最后将结果赋值给变量count并输出。
相关问题
js 统计一个字符串里面出现次数
你可以使用 JavaScript 的正则表达式和字符串方法来统计一个字符串中某个子字符串出现的次数。以下是一个示例代码:
```javascript
function countOccurrences(string, subString) {
// 使用正则表达式创建匹配子字符串的模式
const pattern = new RegExp(subString, 'g');
// 使用 match 方法获取匹配结果数组
const matches = string.match(pattern);
// 返回匹配结果数组的长度,即出现次数
return matches ? matches.length : 0;
}
// 示例用法
const string = 'Hello, hello, hello!';
const subString = 'hello';
const occurrences = countOccurrences(string, subString);
console.log(`'${subString}' 出现了 ${occurrences} 次。`);
```
在上述示例中,`countOccurrences` 函数接受两个参数:`string` 表示待统计的字符串,`subString` 表示要统计出现次数的子字符串。函数内部通过创建正则表达式模式来匹配子字符串,并使用 `match` 方法来获取匹配结果数组。最后返回匹配结果数组的长度,即为子字符串出现的次数。
统计一个字符串在另一个字符串中出现的次数
可以使用Python中的count()函数来统计一个字符串在另一个字符串中出现的次数。例如:
```python
s = "hello world"
count = s.count("l")
print(count) # 输出:3
```
上面的代码中,count()函数统计字符串s中字符“l”的出现次数。输出结果为3,表示“l”在字符串s中出现了3次。