Java 接收两个字符串并返回一个新字符串,同时删除第二个字符串(无if语句)

Java 接收两个字符串并返回一个新字符串,同时删除第二个字符串(无if语句),java,Java,我不是在问答案,我只是在寻找一个暗示。这是一个家庭作业,我必须写一个方法,接收两个字符串并返回一个新字符串,它必须看起来像原始字符串,但第二个字符串的出现被删除。我不能使用if语句 public class Main { public static void main(String[]args) { System.out.println(without("operation", "ra")); System.out.println(without("che

我不是在问答案,我只是在寻找一个暗示。这是一个家庭作业,我必须写一个方法,接收两个字符串并返回一个新字符串,它必须看起来像原始字符串,但第二个字符串的出现被删除。我不能使用if语句

public class Main {
    public static void main(String[]args) {
        System.out.println(without("operation", "ra"));
        System.out.println(without("checkers", "ers"));
        System.out.println(without("checkers", "ch"));
    }

    public static String without(String x, String y) {
        int indexNumb = x.lastIndexOf(y);
        int lastIndex = x.length();
        String firstWord = x.substring(0, indexNumb);
        String secondHalf = x.substring(indexNumb + 2, lastIndex);
        return firstWord + secondHalf;
    }
}
我的输出是:

opetion
checks
eckers
我应该得到:

opetion
check
eckers

这应该可以做到。您正在为后半部分设置固定长度,并将其替换为y。长度将修复它

public class Main {

public static void main(String[]args) {
    System.out.println(without("operation", "ra"));
    System.out.println(without("checkers", "ers"));
    System.out.println(without("checkers", "ch"));
}

public static String without(String x, String y) {
    int indexNumb = x.lastIndexOf(y);
    int lastIndex = x.length();
    String firstWord = x.substring(0, indexNumb);
    String secondHalf = x.substring(indexNumb + y.length(), lastIndex);
    return firstWord + secondHalf;
}

}

在以下代码行中:

假设y,即要删除的字符串长度为两个字符。这个假设适用于第一个和第三个测试用例,但不适用于第二个测试用例,这就是为什么输出中会有一个额外的字母

请使用以下替代品:

String secondHalf = x.substring(indexNumb + y.length(), lastIndex);
最简单的方法是x

如果您尚未学习该命令,或者您不允许使用该命令: 到目前为止,你的解决方案相当不错

String secondHalf = x.substring(indexNumb + 2, lastIndex);
你正在从字符串中剪下两个字母。这适用于第二个字符串,如ra或ch。 要使其适用于任何第二个字符串,只需将2替换为y.length


我会使用String.replace函数。字符串替换函数接受两个参数。首先是要替换的字符串模式,其次是要替换的内容。没有按要求提交完整答案

你说这是家庭作业。然后应该允许您查看字符串的javadoc,并找到一个符合注释中提到的要求的方法

除此之外,你还需要某种形式的条件反射

如果允许使用条件,可以通过递归一次删除一个实例来实现。 如果允许使用循环,则可以循环直到不再找到y为止。 按照您现在的编码方式,如果y不是x的一部分,它将失败

考虑

    System.out.println(without("checkers", "xy"));
    System.out.println(without("mymymy", "y"));

有点像x;如果有效,我们从未学习过该命令,因此它不会获得信任。我们很难知道您学习过或没有学习过字符串类的哪一部分。1在y出现时将字符串拆分为一个数组。2再次将所有部分合并为一个字符串我们学习了如何生成字符串、索引、字符、字符、子字符串、lastIndexOf、length如果找不到y,则此操作失败。此外,它只删除y的最后一个实例。我认为这是在没有if语句的情况下可以得到的最好结果。在我的回答中,我指出了一些其他选项。当然,它们都使用某种条件。这对于我提到的角点情况也是必要的。如果y不是x的一部分,这仍然是失败的!
String secondHalf = x.substring(indexNumb + y.length(), lastIndex);
    System.out.println(without("checkers", "xy"));
    System.out.println(without("mymymy", "y"));