finding matching characters between two strings

Mana :
public class findMatching {
   public static void main(String[] args) {
      String matchOne = "caTch";
      String matchTwo = "cat";
      findMatching(matchOne, matchTwo);
   }

   public static void findMatching(String matchOne, String matchTwo) {
      int lengthOne = matchOne.length();
      int lengthTwo = matchTwo.length();
      char charOne;
      char charTwo;

      while(!matchOne.equals(matchTwo)) {
         for(int i = 0; i < lengthOne && i < lengthTwo; i++) {
            charOne = matchOne.charAt(i);
            charTwo = matchTwo.charAt(i);
            if(charOne == charTwo && lengthOne >= lengthTwo) {
               System.out.print(charOne);
            } else if (charOne == charTwo && lengthTwo >= lengthOne){
               System.out.print(charTwo);
            } else {
               System.out.print(".");
            }
         }
      }
   }
}

I have created a static method called findMatching that takes in two String parameters and then compares them for matching characters. If matching characters are detected, it prints said characters while characters that do not match are represented with an "." instead.

EX: for caTch and cat, the expected output should be ca... where the non-matching characters are represented with "." in the longer string.

Right now however, my program's output only prints out ca. in that it only prints the non-matching characters for the shorter string. I believe the source of the problem may be with the logic of my if statements for lengthOne and lengthTwo.

Asthor :

Your for loop will terminate as soon as you meet the length of the shorter string as you are doing i < lengthOne && i < lengthTwo. So you need to keep the loop going until you get to the end of the longer string, but stop comparing when the shorter string is out of characters.

Something like this would be able to do the job

public static void findMatching(String matchOne, String matchTwo) {
  int lengthOne = matchOne.length();
  int lengthTwo = matchTwo.length();
  char charOne;
  char charTwo;

  for(int i = 0; i < lengthOne || i < lengthTwo; i++) {
    if(i < lengthOne && i < lengthTwo) {
        charOne = matchOne.charAt(i);
        charTwo = matchTwo.charAt(i);
        if (charOne == charTwo) {
           System.out.print(charTwo);
        } else {
           System.out.print(".");
        }
    } else {
       System.out.print(".");
    }

  }
}

I am not sure what the point of the while loop is as it would make the program run forever, however maybe you want that as an if?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356725&siteId=1