从 java 中的字符串中删除常见的字符串字符
Remove common string charaters from a string in java
嗨,我有两个字符串
str1="abcd"
str2="apcd"
现在我想从第二个字符串中删除所有常见字符。我怎样才能做到这一点?我用 HashSet
试过了,但是有什么简单的方法吗?请帮助我。
提前致谢
您可以使用 String#replaceAll
在一行中完成。您使用方括号之间的第一个字符串作为要匹配的正则表达式。这是有效的,因为 [abc]
匹配 a
、b
或 c
.
public static String removeCommon(String string1, String string2) {
return string2.replaceAll("[" + string1 + "]", "");
}
示例代码
public static void main(String[] args) {
System.out.println(removeCommon("abcd", "apcd"));
}
输出
p
使用 Guava 的示例:
package org.example;
import com.google.common.base.CharMatcher;
public class CharRemover {
public static void main(final String[] args) {
final String str1 = "abcd";
final String str2 = "apcd";
System.out.println(CharMatcher.anyOf(str1).and(
CharMatcher.anyOf(str2)).removeFrom(str2));
}
}
StringBuffer sb1 = new StringBuffer("abcd");
StringBuffer sb2 = new StringBuffer("apcd");
for(int i=0;i<sb1.length();i++){
for(int j=0;j<sb2.length();j++){
if(sb1.charAt(i) == sb2.charAt(j)){
sb2.deleteCharAt(j);
}
}
}
System.out.println(sb2);
如有错误请见谅。
因为我是 java.
的新手
public class Stack {
static int count=0;
static int index=0;
public static void main(String args[])
{
String str1="abcdg";
String str2="apcdj";
int i=0;
char buffer[]=new char[str1.length()];
for(i=0;i<str1.length();i++)
{
char s=str1.charAt(i);
char s1=str2.charAt(i);
if(s!=s1)
{
int j=i;
j=i-count;
buffer[j]=s1;
}
else
{
count++;
}
}
str2=String.valueOf(buffer);
System.out.println(str2);
}
}
嗨,我有两个字符串
str1="abcd"
str2="apcd"
现在我想从第二个字符串中删除所有常见字符。我怎样才能做到这一点?我用 HashSet
试过了,但是有什么简单的方法吗?请帮助我。
提前致谢
您可以使用 String#replaceAll
在一行中完成。您使用方括号之间的第一个字符串作为要匹配的正则表达式。这是有效的,因为 [abc]
匹配 a
、b
或 c
.
public static String removeCommon(String string1, String string2) {
return string2.replaceAll("[" + string1 + "]", "");
}
示例代码
public static void main(String[] args) {
System.out.println(removeCommon("abcd", "apcd"));
}
输出
p
使用 Guava 的示例:
package org.example;
import com.google.common.base.CharMatcher;
public class CharRemover {
public static void main(final String[] args) {
final String str1 = "abcd";
final String str2 = "apcd";
System.out.println(CharMatcher.anyOf(str1).and(
CharMatcher.anyOf(str2)).removeFrom(str2));
}
}
StringBuffer sb1 = new StringBuffer("abcd");
StringBuffer sb2 = new StringBuffer("apcd");
for(int i=0;i<sb1.length();i++){
for(int j=0;j<sb2.length();j++){
if(sb1.charAt(i) == sb2.charAt(j)){
sb2.deleteCharAt(j);
}
}
}
System.out.println(sb2);
如有错误请见谅。 因为我是 java.
的新手public class Stack {
static int count=0;
static int index=0;
public static void main(String args[])
{
String str1="abcdg";
String str2="apcdj";
int i=0;
char buffer[]=new char[str1.length()];
for(i=0;i<str1.length();i++)
{
char s=str1.charAt(i);
char s1=str2.charAt(i);
if(s!=s1)
{
int j=i;
j=i-count;
buffer[j]=s1;
}
else
{
count++;
}
}
str2=String.valueOf(buffer);
System.out.println(str2);
}
}