编写一个字符浏览器,输入字符串以及需要查找的字符或字符串,浏览器自动定位所有出现该字或字符串的位置

运行结果如图所示。哪个高手来指导一下
2024-10-31 10:19:42
推荐回答(1个)
回答1:


public class Test {
public static void main(String args[]) {
System.out.println("Please enter one sentence:");
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sentence = scanner.nextLine();
System.out.println("Please enter the key:");
String pattern = scanner.next();
int index = -1;
while ((index = sentence.indexOf(pattern, index + 1)) >= 0) {
System.out.print(index + " ");
}
}
}