import java.util.Scanner;public class Test5 { public static String getInputString(int type) { Scanner scan = new Scanner(System.in); switch (type) { case 1:System.out.print("输入字串:");break; case 2:System.out.print("要查找字串为:");break; case 3:System.out.print("要替换的字串为:");break; } String s=scan.nextLine(); return s; } public static void main(String[] args) { String str=getInputString(1); String target=getInputString(2); String replace=getInputString(3); int i=0; while (str.indexOf(target)!=-1) { i+=1; str=str.replaceFirst(target, replace); } System.out.println("共替换"+i+"次"); System.out.println("替换后结果如下:"); System.out.println(str); }}
用一个正则表达式呗!^\\$\\{(\\d)\\}$ 追问 不行啊 追答 String regex = "\\$\\{(\\w*)\\}"Matcher matcher = Pattern.compile(regext).matcher("fdfwefw${1} fdfsd");while (matcher.find()) { String key = matcher.group(1);}真的想学好,就应该多动动手,去看看Pattern的API文档,里面详细极了!