【问题标题】:Java method that accepts two strings as arguments and returns the first string with all instances of the second string removed接受两个字符串作为参数并返回第一个字符串并删除第二个字符串的所有实例的 Java 方法
【发布时间】:2013-03-30 02:42:08
【问题描述】:

我需要创建一个方法,正如标题所说,接受两个字符串作为参数,接受第一个字符串,并删除第二个字符串中的所有字母。

例如。 (“你今天过得怎么样”,“嘿”)

会返回“ow ar ou do toda”

我有这个

    while(counter < length){
        String letter = phrase.substring(counter, counter+1);
        if(!letter.equals(second)){
            filtered = filtered + letter;
        }
        counter++;
    }

如果它只有一个字母,则有效。我无法弄清楚如何使用第二个字符串中的多个字母使其工作。

我不能使用替换或数组。

【问题讨论】:

  • contains 方法在这里对你很有帮助。
  • 您可以将字符串转换为 Char 数组,然后进行两次迭代,与您已经尝试过的相差不远。
  • 我不明白为什么你不能使用带有“交叉点”的数组,但是如果你说这段代码对你有用,为什么不把它放在另一个循环中呢?

标签: bluej


【解决方案1】:

这是一种方法的伪代码:

assign 1:st string to resultString

for each letter in 2:nd string
    delete instances of that letter in resultString
    by means of methods indexOf, substring and contains

【讨论】:

    【解决方案2】:

    这是你可以使用的东西(可能还有其他方法):

    public static void main(String[] args) {
    
        System.out.println(customStr("How are you doing today", "hey"));
    }
    
    public static String customStr(final String base, final String remove){
        String baseCopy = base.trim();
        String removeCopy = remove.trim();
    
        // Delete all uppercase & lowercase letters using a regex [HEYhey]
        baseCopy = base.replaceAll("[" + removeCopy.toUpperCase(Locale.ENGLISH) 
                + removeCopy.toLowerCase(Locale.ENGLISH) + "]", "");
    
        return baseCopy;
    }
    

    输出是

    你现在在做什么

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多