输入一段字符串求子字符串出现的次数🙏
展开全部
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);
}
}
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);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询