Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

difference between 2 strings 1

Status
Not open for further replies.

johnv20

Programmer
Sep 26, 2001
292
US
Hi,
does anyone know how to compare 2 strings and show the differences ?
 
Well, I think it depends on how you want to show the differences. There's a really simple way you can compare two strings and show the differences if you don't care about position. But if you want the differences between "ABCDE" and "BCDEF" to be shown as "First string starts with A" and "Last string ends with F", then this won't work. This is for simple stuff like "ABCDE" vs. "ABCEE":

(note: not tested)
Code:
public String showDifferences(String s1, String s2)
{
  StringBuffer diffStr=new StringBuffer("");

  int i;
  for(i=0; i<s1.length() && i<s2.length(); i++)
  {
    if(s1.charAt(i)!=s2.charAt(i))
      diffStr.append(&quot;String 1: &quot;+s1.charAt(i)+&quot;  String 2: &quot;+s2.charAt(i)+&quot;\n&quot;);
  }
  if(s1.length() > s2.length())
  {
    diffStr.append(&quot;String 1 extra: &quot;+s1.substring(i));
  }
  else if(s2.length() > s1.length())
  {
    diffStr.append(&quot;String 2 extra: &quot;+s2.substring(i));
  }
  return diffStr.toString();
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top