我是一名学生,正在尝试解决一个问题。
我需要创建一个方法,从另一个字符串中删除指定字符串中找到的任何字符。
因此,如果 String str = "hello world" and String remove = "eo"
,则该方法将返回"hll wrld"
。
我的解决方案设置方式会多次打印出结果字符串,这是我不想要的。是否有简单的解决方法,或者我必须重新设计该方法?
class StringStuff{
public static void main (String [] args){
String str = "This is a string that needs to be changed";
String remove = "iaoe";
System.out.println(removeChars(str, remove));
}
public static String removeChars(String str, String remove){
String newStr = "";
for(int i=0;i<remove.length();i++){
for(int j=0; j<str.length(); j++){
if(str.charAt(j)!=remove.charAt(i)){
newStr = newStr+str.charAt(j);
}
}
}
return newStr;
}
}
更新
谢谢您的回复,我根据您提供的解决方案,想出了另一种“新手”的方法。
public static String removeChar(String str, String remove){
String newStr = "";
boolean match = false;
for(int i = 0; i<str.length(); i++){
for(int j=0; j<remove.length(); j++){
if(str.charAt(i) == remove.charAt(j))
match = true;
}
if(match == false)
newStr = newStr + str.charAt(i);
match = false;
}
return newStr;
}