Home > Software engineering >  Compare two strings and replace matches
Compare two strings and replace matches

Time:11-07

Im very new to Java and I have a following task:

Compare string 1 to string 2 letter by letter and find those that match and replace them with *.

I am completely lost and need some assistance. Here is a bit of code I was able to put together myself.

Scanner sc = new Scanner(System.in);
String str1 =  sc.nextLine();
String str2 =  sc.nextLine();
        
char char1 = str1.charAt(0);
char char2 = str2.charAt(0);
        
for(int i=0; i<str1.length();i  ){
   if(str2.equals(str1)){
                
   }
}

CodePudding user response:

Your code is on the right track. I suggest using a StringBuilder here to build out the two replacement strings:

Scanner sc = new Scanner(System.in);
String str1 =  sc.nextLine();
String str2 =  sc.nextLine();

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();

for (int i=0; i < str1.length(); i  ) {
    char char1 = str1.charAt(i);
    char char2 = str2.charAt(i);
    if (char1 == char2) {
        sb1.append('*');
        sb2.append('*');
    }
    else {
        sb1.append(char1);
        sb2.append(char2);
    }
}

System.out.println("New string1 is: "   sb1.toString());
System.out.println("New string2 is: "   sb2.toString());

Note that this answer assumes that both input strings would have the same length. It makes no attempt to check for this, nor does it consider the behavior for two unequal length strings.

CodePudding user response:

Try this.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    StringBuilder str1 = new StringBuilder(sc.nextLine());
    StringBuilder str2 = new StringBuilder(sc.nextLine());
    for (int i = 0, size = Math.min(str1.length(), str2.length()); i < size;   i)
        if (str1.charAt(i) == str2.charAt(i)) {
            str1.setCharAt(i, '*');
            str2.setCharAt(i, '*');
        }
    System.out.println("str1="   str1   " str2="   str2);
}

input:

abcdefg
cbadex

output:

str1=a*c**fg str2=c*a**x
  • Related