简体   繁体   English

从另一个字符串中删除一组非连续字符(作为字符串)?

[英]Remove a set of nonconsecutive characters (as a String) from another String?

I need to generate s3 string by removing from s1 all characters appearing in s2. 我需要通过从s1中删除出现在s2中的所有字符来生成s3字符串。

For example : 例如 :

String s1 = "Computer"; 
String s2 = "mur";

Result must be : "Copte" 结果必须为: "Copte"

I tried to do: s3 = s1.replace(s2, ""); 我试图做: s3 = s1.replace(s2, ""); but it does not work. 但它不起作用。 I get the same word: computer . 我得到一个相同的词: computer

You can use replaceAll witch accept regex : 您可以使用replaceAll女巫接受正则表达式:

String result = s1.replaceAll(String.format("[%s]", s2), "");// Output Copte

If your string contain some special characters, for example } { ) ( . - this character can be part from the regex syntax, in this case you have to escape them, you can just use Pattern.quote(s2) like this : 如果您的字符串包含一些特殊字符,例如} { ) ( . - 。-此字符可以是regex语法的一部分,在这种情况下,您必须转义它们,您可以像这样使用Pattern.quote(s2)

String result = s1.replaceAll(String.format("[%s]", Pattern.quote(s2)), "");

s1.replace(s2, "") works when s2 is substring of s1 . s2s1子字符串时s1.replace(s2, "")起作用。 However, mur is not a substring of Computer . 但是, mur不是Computer的子字符串。 Since m u r are substrings of Computer , you can remove them separatly. 由于m u r是子Computer ,你可以separatly删除它们。

String s1="Computer", s2="mur";
for (char c : s2.toCharArray()) {  // create a char array [m, u, r]
    s1 = s1.replace(String.valueOf(c), "");  // remove them separatly
}
System.out.print(s1);

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

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