简体   繁体   English

从 String Java 中删除一串字母

[英]Removing a string of letters from a String Java

Okay been on this for a while now and have gone through many different versions of doing this the goal is to have a method like remove("pdi") and it will return "eter er cke"好的,现在已经有一段时间了,并且已经经历了许多不同的版本,目标是有一个像 remove("pdi") 这样的方法,它会返回 "eter er cke"

The remove() function has to remove all the characters in myString matching with characters of args passed as an argument to the function. remove() function 必须删除 myString 中与作为参数传递给 function 的args字符匹配的所有字符。

public class CodioCustomString {

public static void main(String[] args) {
    System.out.println(remove("pdi"));
    
}

//2 Variables
static String myString = "peter piper picked";
boolean isSet;

//constructor

public static String remove(String arg) {
    char[] chars = arg.toCharArray();
    StringBuilder newString = new StringBuilder(myString);
    for(char i: chars) {
        for(int k = 0; k < myString.length(); k++) {
            if(i == myString.charAt(k)) {
                newString.deleteCharAt(k);
                continue;
            }
            else {
                continue;
            }

        }
        
        }
    return newString.toString();
}

Here are three methods to do it.这是执行此操作的三种方法。 The methods take two argument.这些方法有两个参数。

  • the target string subject to removal要删除的target字符串
  • the source string of characters to be removed.要删除的source字符串。
String result1 = remove1("peter piper picked", "pbi");
System.out.println(result1);

String result2 = remove2("peter piper picked", "pbi");
System.out.println(result2);

String result3 = remove3("peter piper picked", "pbi");
System.out.println(result3);

prints印刷

eter er cked
eter er cked
eter er cked

Explanations说明

remove1移除1

The easiest way is as follows:最简单的方法如下:

  • use replaceAll which takes a regular expression使用带有正则表达式的replaceAll
  • [abc] is a character class which matches any of those characters. [abc]是匹配任何这些字符的字符 class。 So simply create one by surrounding your letters to be removed with brackets.因此,只需通过用方括号包围要删除的字母来创建一个。
  • replace the occurrence of those characters with an empty string.用空字符串替换这些字符的出现。
public static String remove1(String target, String toBeRemoved) {
    return target.replaceAll("[" + toBeRemoved + "]", "");
}

remove2移除2

If you prefer to do it in a loop you can do the following:如果您更喜欢在循环中执行此操作,则可以执行以下操作:

  • simply iterate across the characters of the string.简单地遍历字符串的字符。
  • if the removal letters contains the character, ignore it.如果删除字母包含该字符,则忽略它。
  • else append it to a StringBuilder否则 append 到StringBuilder
public static String remove2(String target, String toBeRemoved) {
    StringBuilder sb = new StringBuilder();
    for (char ch : target.toCharArray()) {
        if (!toBeRemoved.contains(Character.toString(ch))) {
            sb.append(ch);
        }
    }
    return sb.toString();
}

remove3删除3

This method streams the characters.此方法流式传输字符。

  • map each character to a string map 每个字符到一个字符串
  • filter out the ones to be removed过滤掉要删除的
  • collect into a new String using Collectors.joining()使用Collectors.joining()收集到一个新的字符串中
public static String remove3(String target, String toBeRemoved) {
    return target.chars().mapToObj(Character::toString)
            .filter(Predicate.not(toBeRemoved::contains)))
            .collect(Collectors.joining());
}
    

The problem is that you are comparing the length of myString in the for loop which is fixed.问题是您在固定的 for 循环中比较 myString 的长度。 Instead you should be comparing it with the length of StringBuilder ( newString in this case) as you are reducing the length when performing the delete operation.相反,您应该将它与 StringBuilder 的长度(在本例中为 newString )进行比较,因为您在执行删除操作时正在减少长度。

Also, the time complexity (tc) of the above code is O(n*k) where n is the length of the string and k the length of string that needs to be removed.此外,上述代码的时间复杂度 (tc) 为 O(n*k),其中 n 是字符串的长度,k 是需要删除的字符串的长度。

You can improve the time complexity by storing the character in a set and then iterating the newString and performing the remove operation.您可以通过将字符存储在一个集合中,然后迭代 newString 并执行删除操作来提高时间复杂度。

public class CodioCustomString {
    public static void main(String[] args) {
        System.out.println(remove("pdi"));
        System.out.println(remove2("pdi"));
    }

    // 2 Variables
    static String myString = "peter piper picked";
    boolean isSet;

    /** tc - o(nk) where k is length of args string and n is length of string */
    private static String remove(String arg) {
        char[] chars = arg.toCharArray();
        StringBuilder newString = new StringBuilder(myString);
        for (char i : chars) {
            for (int k = 0; k < newString.length(); k++) {
                if (i == newString.charAt(k)) {
                    newString.deleteCharAt(k);
                    k--;
                } else {
                    continue;
                }

            }

        }
        return newString.toString();
    }

    /**
     * tc - o(n) + o(k) where k is length of args string and n is length of string
     */
    private static String remove2(String arg) {
        char[] chars = arg.toCharArray();
        Set<Character> set = new HashSet<>();
        for (char i : chars) {
            set.add(i);
        }
        StringBuilder newString = new StringBuilder(myString);

        for (int k = 0; k < newString.length(); k++) {
            if (set.contains(newString.charAt(k))) { // set.contains is o(1) operations
                newString.deleteCharAt(k);
                k--;
            }

        }

        return newString.toString();
    }
}

and the expected output:和预期的 output:

eter er cke
eter er cke

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM