用Java写1、 给定一个字符串,判断该字符串中是否包含某个子串.如果包含,求出子串的所有出现位置,:"he is a good student and he is a good boy too"中,"good"子串的出现位置为: 9,34,字符串和子串均由用户输入
时间: 2024-06-10 07:05:02 浏览: 68
java 判断字符串是否包含子串的方法
好的,以下是用Java实现上述需求的代码:
```
import java.util.ArrayList;
import java.util.Scanner;
public class SubstringSearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串:");
String str = scanner.nextLine();
System.out.println("请输入子串:");
String subStr = scanner.nextLine();
ArrayList<Integer> result = new ArrayList<>();
int index = str.indexOf(subStr);
while (index != -1) {
result.add(index);
index = str.indexOf(subStr, index + 1);
}
if (result.size() == 0) {
System.out.println("该字符串中不包含该子串。");
} else {
System.out.println("该字符串中共出现了" + result.size() + "个\"" + subStr + "\"子串,位置分别为:" + result.toString());
}
}
}
```
Hope it helps!
阅读全文