Bakslat Bakslat - 2 months ago 8
Java Question

Method to do compare and change single characters in a string

I need to do a method to check two string for example bod and bot or crab and rab. The method needs to print out what the user must do in order to make them equal. For example in bod and bot it will print "replace,2,d in the string". I used this code which seems to work.

if(a.length()==b.length()){
int i;
for(i=0; i<=a.length(); i++){
if(a.charAt(i)!=b.charAt(i)){
return "replace,"+ i + "," + b.charAt(i);
}
}
}


But I am having troubles if the two string are not equal in size. I use this but it doesn't work because one of the strings is bigger.

int aS = a.length();
int bS = b.length();
if(bS - aS == 1){
int i;
for(i=0; i<=b.length(); i++){
if(b.charAt(i)!=a.charAt(i)){
return "remove," + i;
}
}
}


Can you guys give me a suggestion what method I can use to check which is the extra letter or vice versa a letter I can add and then return a string saying either to remove a character or add an extra one. Thank you

Answer

Maybe something like this?

public ArrayList<String> createConversionList(String primary, String secondary){
  //Determine which string is shorter.
  String shorter;
  String longer;
  boolean primaryIsShorter = false;
  if (primary.length() >= secondary.length()){
    longer = primary;
    shorter = secondary;
  } else{
    longer = secondary;
    shorter = primary;
    primaryIsShorter = true;
  }

  //Fills an array with all the character positions that differ between the
  //two strings, using the shorter string as the base.
  int[] posOfCharsToChange = new int[shorter.length()];
  for(int i = 0; i < shorter.length(); i++){
    if(shorter.charAt(i) != longer.charAt(i)){
      posOfCharsToChange[i] = i;
    } else{
      posOfCharsToChange[i] = -1;
    }
  }

  //Adds to an ArrayList all of the "Replace" strings.
  ArrayList<String> conversionList = new ArrayList();
  for(int pos: posOfCharsToChange){
    if(pos != -1){
      String s = "Replace " + secondary.charAt(pos) + " with " + primary.charAt(pos) + ". \n";
      conversionList.add(s);
    }
  }

  //Depending on which string was bigger, either adds "Add" or "Remove"
  //strings to the ArrayList. If the strings were the same size, does
  //nothing.
  if(primary.length() != secondary.length()){
    if(primaryIsShorter){
      for(int i = primary.length(); i < secondary.length(); i++){
        String s = "Remove " + secondary.charAt(i) + ". \n";
        conversionList.add(s);
      }
    }
    else{
      for(int i = secondary.length(); i < primary.length(); i++){
        String s = "Add " + primary.charAt(i) + ". \n";
        conversionList.add(s);
      }
    }
  }

  return conversionList;
}