我正在尝试用JAVA为";减去";给定字符串中的子字符串。例如,如果我的输入是";委员会;以及";满足";输出应该是"0";comit";。
到目前为止,这就是我所拥有的,但它并没有做它应该做的。我很确定问题出在代码末尾的嵌套for循环的迭代上,但我不知道问题出在哪里,也不知道如何解决。
public static String remove(String str1, String str2) {
char[] char1 = new char[str1.length()];
char[] char2 = new char[str2.length()];
char[] char3 = new char[str1.length()];
int k = 0;
for (int i = 0; i < str1.length(); i++) { // converts str1 to char1
char1[i] = str1.charAt(i);
}
for (int j = 0; j < str2.length(); j++) { // converts str2 to char2
char2[j] = str2.charAt(j);
}
for (int i = 0; i < char1.length; i++) { // loops through char1
for (int j = 0; j < char2.length; j++) {
if (char1[i] != char2[j]) {
char3[k] = char1[i];
}
}
k++;
}
return String.valueOf(char3);
}
在要删除的字符数组上循环时,可以使用replaceFirst
。应使用特定字符标记已删除的原始字符串上的字符,以便以后重新生成结果时可以重新访问。
public class Test1 {
public static void main(String[] args) {
String result = remove("committee", "meet");
System.out.println(result);
}
//str1 is the original string, str2 is the
//array of chars to be removed from str1
public static String remove(String str1, String str2) {
for (int i = 0; i < str2.length(); i++) {
//tag the one deleted using specific character
str1 = str1.replaceFirst(Character.toString(str2.charAt(i)), "#");
} //end for
StringBuilder sb = new StringBuilder();
//Populate the non deleted chars
for (int i = 0; i < str1.length(); i++) {
//only copy character which has not yet been deleted
if (str1.charAt(i) != '#') {
sb.append(str1.charAt(i));
} //end if
} //end for
return sb.toString();
}
}
样本输出:
comit
您可以将StringBuilder
用于此目的:
public static void main(String[] args) {
System.out.println(remove("committee", "meet")); // comit
}
public static String remove(String str1, String str2) {
// convert first string to StringBuilder
StringBuilder sb = new StringBuilder(str1);
// iterate over the characters of the second string
for (char ch : str2.toCharArray()) {
// index of the first occurrence of
// this character in the first string
int i = sb.indexOf(String.valueOf(ch));
// if present
if (i >= 0) {
// remove this character
sb.deleteCharAt(i);
}
}
return sb.toString();
}
另请参阅:将char[][]转换为char[]
这不是更容易吗:
public class StringSubtract {
public static void main(String[] args) {
String result = subtract("committee", "meet");
System.out.println(result);
}
public static String subtract(String str1, String str2) {
for (int i = 0; i < str2.length(); i++) {
str1 = str1.replaceFirst(Character.toString(str2.charAt(i)), "");
} //end for
return str1;
}
}