【问题标题】:How to remove substring from a String? [closed]如何从字符串中删除子字符串? [关闭]
【发布时间】:2021-03-17 10:35:48
【问题描述】:

我想与您分享我的代码以帮助我改进。

我需要编写一个函数,它返回一个由string1 减去string2 的所有字符组成的String

这是我尝试过的,不幸的是它效果不佳:

public static String remove(String str1, String str2) {
    String empty = "";

    for (int i = 0; i < str2.length(); i++) { // hello ll
        for (int j = 0; j < str1.length(); j++) {
            if (str2.charAt(i) != str1.charAt(j)) {
                empty = empty + str1.charAt(j);

            }
        }
    }
    return empty;
}

【问题讨论】:

标签: java string function replace substring


【解决方案1】:

您可以使用indexOf 来检查第二个String 中是否不存在字符。目前,在确定是否应添加当前字符之前,您不会检查第二个String 的所有字符。此外,最好使用StringBuilder 而不是在循环内连接。

public static String remove(String str1, String str2) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str1.length(); i++) {
        if (str2.indexOf(str1.charAt(i)) == -1) {
            sb.append(str1.charAt(i));
        }
    }
    return sb.toString();
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    public static String remove(String str1, String str2) {
        for (int i = 0; i < str2.length(); i++)
            str1 = str1.replace(str2.charAt(i) + "", "");
        return str1;
    }
    

    从字符串 1 中,您将字符串 2 中的所有字符替换为 ""。

    【讨论】:

      【解决方案3】:

      Stringstring1减去string2的所有字符组成

      public static void main(String[] args) {
          System.out.println(remove("hello", "ll")); // heo
          System.out.println(remove("hello", "eo")); // hll
          System.out.println(remove("hello", "lo")); // he
      }
      
      public static String remove(String str1, String str2) {
          return str1.codePoints()
                  .filter(ch -> !str2.contains(Character.toString(ch)))
                  .mapToObj(Character::toString)
                  .collect(Collectors.joining());
      }
      

      【讨论】:

        【解决方案4】:

        在您的解决方案中,对于第一个字符串中的每个字符,您迭代第二个字符串中的字符,如果两者不同,则将字符附加到结果中。这不是预期的行为 - 只有当它与第二个字符串中的 all 字符不同时,您才需要附加该字符。

        尽可能保持你分享的方法的格式,你会想做这样的事情:

        public static String remove(String str1, String str2) {
            String empty = "";
            
            for (int i = 0; i < str2.length(); i++) {
                boolean found = false;
                for (int j = 0; j < str1.length() && !found; j++) {
                    if (str2.charAt(i) == str1.charAt(j)) {
                        found  = true;
                    }
                }
                if (!found) {
                    empty += str1.charAt(i)
            }
            return empty;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-08
          • 1970-01-01
          • 2011-10-15
          • 2019-12-24
          • 2015-10-04
          相关资源
          最近更新 更多