编写一个方法,输出在一个字符串中,指定字符串出现的次数
时间: 2023-04-23 09:04:43 浏览: 83
可以使用字符串的 count() 方法来实现,该方法返回指定子字符串在原字符串中出现的次数。
示例代码如下:
```python
def count_substring(string, sub):
return string.count(sub)
# 测试
s = "hello world, hello python, hello AI"
print(count_substring(s, "hello")) # 输出 3
```
其中,count_substring() 方法接受两个参数,分别为原字符串和指定子字符串,返回子字符串在原字符串中出现的次数。在上面的示例中,我们测试了一个字符串中 "hello" 出现的次数。
相关问题
编写一个方法输出在一个字符串中指定字符出现的字数
可以使用以下方法来输出指定字符出现的次数:
```python
def count_char(string, char):
count = 0
for i in string:
if i == char:
count += 1
return count
```
其中,`string`表示要搜索的字符串,`char`表示要计数的字符。该方法使用了一个循环来遍历字符串中的每个字符,如果这个字符和指定的字符相同,则计数器加1。最后返回计数器的值,即指定字符在字符串中出现的次数。
使用Java编写一个方法,输出一个字符串中指定字符串出现的次数。
好的,这里是一个Java方法可以实现您的要求:
```java
public static int countSubstring(String str, String subStr) {
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
```
这个方法接收两个参数:要搜索的字符串 `str` 和要计数的子字符串 `subStr`。它使用 `indexOf` 方法来找到子字符串在主字符串中的位置,如果找到了,它会增加计数器并且将查找的起始位置移动到子字符串之后。最后,它会返回计数器的值,即子字符串在主字符串中出现的次数。
您可以使用以下代码来测试:
```java
String str = "hello world, world is beautiful world";
String subStr = "world";
int count = countSubstring(str, subStr);
System.out.println("The substring \"" + subStr + "\" occurs " + count + " times in the string \"" + str + "\".");
```
输出将会是:
```
The substring "world" occurs 3 times in the string "hello world, world is beautiful world".
```