1 25 26 package net.killingar; 27 28 public class WordDiff 29 { 30 private String dumpDelText(DelimitedString str, int start, int end) 31 { 32 StringBuffer sb = new StringBuffer (); 33 34 sb.append("<strike>"); 35 sb.append(str.getSegmentsBetween(start, end)); 36 sb.append("</strike>"); 37 38 return sb.toString(); 39 } 40 41 private String dumpAddText(DelimitedString str, int start, int end) 42 { 43 StringBuffer sb = new StringBuffer (); 44 45 sb.append("<b>"); 46 sb.append(str.getSegmentsBetween(start, end)); 47 sb.append("</b>"); 48 49 return sb.toString(); 50 } 51 52 public String compareStrings(String source, String dest) 53 { 54 DelimitedString str1 = new DelimitedString(source); 55 DelimitedString str2 = new DelimitedString(dest); 56 int str1Idx = 0; 57 int str2Idx = 0; 58 int delTextStart = -1; 59 int addTextStart = -1; 60 61 StringBuffer result = new StringBuffer (); 62 63 while(true) 64 { 65 String s1 = str1.getSegment(str1Idx); 67 String s2 = str2.getSegment(str2Idx); 68 69 70 if(s1 == null || s2 == null) 72 { 73 74 if(delTextStart != -1) 77 result.append(dumpDelText(str1, delTextStart, DelimitedString.END)); 78 else if(s1 != null) 79 result.append(dumpDelText(str1, str1Idx, DelimitedString.END)); 80 81 if(addTextStart != -1) 84 result.append(dumpAddText(str2, addTextStart, DelimitedString.END)); 85 else if(s2 != null) 86 result.append(dumpAddText(str2, str2Idx, DelimitedString.END)); 87 88 break; 90 } 91 92 if(s1.equals(s2)) 94 { 95 96 if(delTextStart != -1 && delTextStart != str1Idx) 98 result.append(dumpDelText(str1, delTextStart, str1Idx)); 99 100 if(addTextStart != -1 && addTextStart != str2Idx) 102 result.append(dumpAddText(str2, addTextStart, str2Idx)); 103 104 delTextStart = addTextStart = -1; 106 107 result.append(s1); 109 result.append(" "); 110 111 str1Idx++; 113 str2Idx++; 114 115 continue; 116 } 117 else 118 { 119 if(delTextStart == -1) delTextStart = str1Idx; 122 if(addTextStart == -1) addTextStart = str2Idx; 123 124 boolean found = false; 125 126 for(int i = str1Idx + 1; str1.getSegment(i) != null; i++) 129 { 130 131 if(str1.getSegment(i).equals(s2)) 133 { 134 135 found = true; 137 str1Idx = i; 138 break; 139 } 140 } 141 142 if(!found) 145 { 146 str2Idx++; 147 } 148 } 149 150 } 151 152 return result.toString(); 154 } 155 156 public static void main(String args[]) 157 { 158 System.out.println(new WordDiff().compareStrings("This is a really long sentence", "This is a short sentence")); 159 System.out.println(new WordDiff().compareStrings("This is a test", "This was a test")); 160 System.out.println(new WordDiff().compareStrings("If this was a test of the emergency broadcast system", "this was a test of the emergncy broadcast system")); 161 System.out.println(new WordDiff().compareStrings("This is new stuff only found once", "All stuff is new only once")); 162 } 163 } | Popular Tags |