Java 我们如何比较两个字符串并删除重复的字符串
输入: 输出:Java 我们如何比较两个字符串并删除重复的字符串,java,Java,输入: 输出: String str1="AUTOMATION " ; String str2="SELENIUM". 使用以下命令: String str1="ATOATO" ; String str2="SELE"; 公共类公共字符{ public void removeCommonCharacter(字符串s1、字符串s2){ 字符串commonChars=“”; 对于(int i=0;i
String str1="AUTOMATION " ; String str2="SELENIUM".
使用以下命令:
String str1="ATOATO" ; String str2="SELE";
公共类公共字符{
public void removeCommonCharacter(字符串s1、字符串s2){
字符串commonChars=“”;
对于(int i=0;i
要删除两个字符串中的常用字符,请使用以下方法:
public class CommonCharacter {
public void removeCommonCharacter(String s1, String s2){
String commonChars = "";
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (s1.charAt(i) == s2.charAt(j)) {
commonChars += s1.charAt(i);
}
}
}
for(int i = 0; i < commonChars.length(); i ++) {
String charToRemove = commonChars.charAt(i)+"";
s1 = s1.replace(charToRemove, "");
s2 = s2.replace(charToRemove, "");
}
System.out.println("After removing common character " + s1);
System.out.println("After removing common character " + s2);
}
public static void main(String[] args){
CommonCharacter commonCharacter = new CommonCharacter();
commonCharacter.removeCommonCharacter("AUTOMATION", "SELENIUM");
}
}
public void removeDuplicateChar(字符串s1、字符串s2){
字符串newS1=s1,newS2=s2;
ArrayList s1Arr=新的ArrayList();
ArrayList s2Arr=新的ArrayList();
对于(int i=0;i
这不是最简单或最快的方法,但它可以完成任务。一种简单的方法是找到字符串中字符集的交集,并替换字符串中交集的字符
public void removeDuplicateChar(String s1, String s2) {
String newS1 = s1, newS2 = s2;
ArrayList<Integer> s1Arr = new ArrayList<Integer>();
ArrayList<Integer> s2Arr = new ArrayList<Integer>();
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (s1.charAt(i) == s2.charAt(j)) {
s1Arr.add(i);
s2Arr.add(j);
}
}
}
for (int k : s1Arr) {
newS1 = newS1.replace((String) (s1.charAt(k) + ""), "");
}
for (int l : s2Arr) {
newS2 = newS2.replace((String) (s2.charAt(l) + ""), "");
}
System.out.println("The modified Strings are: "+ newS1 +" "+ newS2);
}
注意事项:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
String str1 = "AUTOMATION ";
String str2 = "SELENIUM";
Set<String> s1 = new HashSet<>(Arrays.asList(str1.split("")));
Set<String> s2 = new HashSet<>(Arrays.asList(str2.split("")));
s1.retainAll(s2);// Intersection of s1 and s2
String regex = "[" + String.join("", s1.toArray(new String[0])) + "]";
str1 = str1.replaceAll(regex, "");
str2 = str2.replaceAll(regex, "");
System.out.println(str1);
System.out.println(str2);
}
}
String#split(“”
将字符串
拆分为字符串数组,如字符串
字符串
,该字符串由CharSequence
元素的副本和指定分隔符的副本组成“[”+String.join(“,s1.toArray(新字符串[0]))+“]”
通过附加交集的[
+字符+]
来创建交集尝试了equals(),但您的输入与输出有什么关系?它与比较有什么关系?到目前为止做了什么?重复的单词或重复的字符?Selenium与字符串比较有什么关系?这是否回答了您的问题?
ATOATO
SELE