编写java代码,输入一个字符串以及需要查找的字符串,显示所有出现该字符串的位置。

2024-10-31 10:20:30
有4个网友回答
网友(1):

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTestHarnessV5 {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.printf("输入你要查找的文字: ");
Pattern pattern = Pattern.compile(scanner.nextLine());
System.out.printf("输入字符串: ");
Matcher matcher = pattern.matcher(scanner.nextLine());
boolean found = false;
while (matcher.find()) {
System.out.printf("找到 \"%s\" 开始下标 %d 结束下标 %d.%n",
matcher.group(), matcher.start(), matcher.end());
found = true;
}
if (!found) {
System.out.printf("没有找到.%n");
}
}
}
}

网友(2):

public static void main(String[] args) { String str1 = "ajglagjejlag"; String str2 = "ag"; int countLocation = 0; if (str1.contains("ag")) { String[] strings = str1.split(str2); for (int i = 0; i < strings.length; i++) { System.out.println(strings[i]); if (i == 0) { countLocation += strings[i].length(); } else { countLocation = countLocation + strings[i].length() + str2.length(); } System.out.println(str1+"中,第" + (i + 1) + "个匹配的" + str2 + "开始位置:" + countLocation); } } } 根据你的需要修改吧~

网友(3):

试试吧!

网友(4):

用正则表达式