Java examples for java.lang:String Replace
replace Difference between two Strings
public class Main { public static void main(String[] argv) { String fst = "java2s.com"; String snd = "java2s.com"; String replaceWith = "b"; System.out.println(replaceDifference(fst, snd, replaceWith)); }//from w ww . j a v a2 s . c o m public static String replaceDifference(String fst, String snd, String replaceWith) { if (fst.equals(snd)) return replaceWith; String prefix = commonPrefix(fst, snd); String postfix = commonPostfix(fst, snd); int minStrLength = Math.min(fst.length(), snd.length()); int fixesLengthSum = prefix.length() + postfix.length(); return fixesLengthSum <= minStrLength ? prefix + replaceWith + postfix : prefix + replaceWith + postfix.substring(fixesLengthSum - minStrLength); } public static String commonPrefix(String fst, String snd) { StringBuilder cp = new StringBuilder(); int minLength = Math.min(fst.length(), snd.length()); fst = fst.substring(0, minLength); snd = snd.substring(0, minLength); for (int i = 0; i < minLength && fst.charAt(i) == snd.charAt(i); i++) cp.append(fst.charAt(i)); return cp.toString(); } public static String commonPostfix(String fst, String snd) { StringBuilder cp = new StringBuilder(); fst = fst.substring(Math.max(0, fst.length() - snd.length()), fst.length()); snd = snd.substring(Math.max(0, snd.length() - fst.length()), snd.length()); for (int i = fst.length() - 1; i >= 0 && fst.charAt(i) == snd.charAt(i); i--) cp.insert(0, fst.charAt(i)); return cp.toString(); } }