7-29 删除字符串中的子串 (20 分)
7-29 删除字符串中的子串 (20 分)
(PTA 基础编程题目集)
7-29 删除字符串中的子串 (20 分)
输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
输入格式:
输入在2行中分别给出不超过80个字符长度的、以回车结束的2个非空字符串,对应S1和S2。
输出格式:
在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串。
输入样例:
Tomcat is a male ccatat
cat
输出样例:
Tom is a male
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str1=sc.nextLine();
String str2=sc.nextLine();
// String str1="Tomcat is a male ccatat";
// String str2="cat";
//当且仅当str1包含指定的 str2时,返回 true。
while(str1.contains(str2)){
// 用 "" 替换此字符串中出现的所有 str2
str1=str1.replaceAll(str2,"");
}
System.out.println(str1);
}
}
附:本题使用了String中的contains,replaceAll。