Java:在字符串中删除特定的字符:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。

时间:2022-01-24 05:45:03
在字符串中删除特定的字符。

题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。

 例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”。

方法1:

package com.jredu.ch12;

/**
* 2、在字符串中删除特定的字符。
题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。
例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”。

*/
import java.util.Scanner;

public class Work2 {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner in = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String num1 = in.next();
System.out.print("请输入第二个字符串:");
String num2 = in.next();

num1=num1.replace("", "-"); //每个字符加个-
String[] first=num1.split("-");
num2=num2.replace("", "-"); //每个字符加个-
String[] second=num2.split("-");

for (int i = 0; i < first.length; i++) {
for (int j = 0; j < second.length; j++) {
if(first[i].equals(second[j])){
num1=num1.replace(first[i], "");
}
}
}
System.out.println("删除后,第一个字符串为:"+num1.replace("-", "" ));


}

}

方法2:

public static void main(String[] args) {
String str1="They are students";
String str2="aeiou";
for(int i=0;i<str2.length();i++){
//int idx=str1.indexOf(str2.charAt(i));
int idx=0;
while((idx=str1.indexOf(str2.charAt(i)))!=-1){
//str1=str1.replace(String.valueOf(str2.charAt(i)), "");
str1=str1.substring(0,idx)+str1.substring(idx+1);
}
}
System.out.println(str1);
}