如何“减去"2给定的字符串在Java中? [英] How to "subtract" 2 given strings In Java?

查看:37
本文介绍了如何“减去"2给定的字符串在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JAVA中创建一种方法,用于减去"代码.给定字符串中的子字符串.例如,如果我的输入是委员会",则和满足"输出应为"comit".

I'm trying to create a method in JAVA for "subtracting" a substring from a given string. For example, if my input is "committee" and "meet" the output should be "comit".

到目前为止,这是我所拥有的,但它没有执行应有的功能.我很确定问题出在代码末尾的嵌套for循环的迭代上,但是我无法弄清楚问题出在哪里或如何解决.

This is what I have so far, but it's not doing what it is supposed to. I'm pretty sure the problem is with the iteration of the nested for loop at the end of the code, but I can't figure out what is the problem or how to fix it.

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

推荐答案

在要删除的字符数组上循环时,可以使用

While looping on the array of character that you wish to delete, you can use replaceFirst. The character on the original string that you have deleted should be tagged with a specific character so that you can revisit later when rebuilding the result.

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

这篇关于如何“减去"2给定的字符串在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆