如何在java中“减去”2个给定的字符串

aurhwmvo  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(294)

我试图用java创建一个方法,从给定的字符串中“减去”子字符串。例如,如果我的输入是“committee”和“meet”,那么输出应该是“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);
}
3pvhb19x

3pvhb19x1#

在要删除的字符数组上循环时,可以使用 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++) {
            str1 = str1.replaceFirst(Character.toString(str2.charAt(i)), "#"); //tag the one deleted using specific character
        } //end for

        StringBuilder sb = new StringBuilder();
        //Populate the non deleted chars
        for (int i=0; i < str1.length(); i++) {
            if (str1.charAt(i) != '#') { //only copy character which has not yet been deleted
                sb.append(str1.charAt(i));
            } //end if
        } //end for
        return sb.toString();
    }   
}

样本输出:

comit
vc6uscn9

vc6uscn92#

这不是更简单吗:

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;
        }
    }

相关问题