Issue
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)){
}
}
Solution
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
Answered By - saka1029 deleted