记录一个子串在整串中出现的次数。 编写一个程序,记录一个子串在整串中出现的次数。例如记录子串”nba”在整串 nbaernbanbaynbauinbaopnba""中出现的次数为6,使用String类的常用方法来计算出现的次数。
时间: 2024-02-11 07:09:10 浏览: 31
好的,这里是Java代码实现:
```
public class SubstringCount {
public static void main(String[] args) {
String str = "nbaernbanbaynbauinbaopnba";
String subStr = "nba";
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
System.out.println(subStr + " 出现的次数为:" + count);
}
}
```
运行结果为:
```
nba 出现的次数为:6
```
其中,使用了String类的indexOf方法来查找子串出现的位置,从而统计出现的次数。
相关问题
编写一个程序,记录一个子串在整串中出现的次数
可以使用字符串的 count() 方法来统计子串在整串中出现的次数。具体实现如下:
```python
s = "hello world"
sub = "l"
count = s.count(sub)
print(count) # 输出 3
```
其中,s 是整串,sub 是要统计的子串,count() 方法返回子串在整串中出现的次数。
Java完成记录一个子串在整串中出现的次数
你可以使用Java中的String类的indexOf()方法来查找子串在整串中的位置,然后使用循环来计算出现次数。以下是示例代码:
```java
public class SubstringCount {
public static int countSubstring(String str, String subStr) {
int count = 0;
int index = str.indexOf(subStr);
while (index != -1) {
count++;
index = str.indexOf(subStr, index + 1);
}
return count;
}
public static void main(String[] args) {
String str = "Java is a programming language. Java is used for web development, mobile apps, and more.";
String subStr = "Java";
int count = countSubstring(str, subStr);
System.out.println("The substring \"" + subStr + "\" appears " + count + " times in the string.");
}
}
```
输出结果:
```
The substring "Java" appears 2 times in the string.
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)