Java - Write code to find difference between two string

Requirements

Write code to find difference between two string

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str1 = "book2s.com";
        String str2 = "ook2s.com";
        System.out.println(difference(str1, str2));
    }/*  w  w  w  .j  a v a2  s . c  o m*/

    public static final String EMPTY_STRING = "";

    public static String difference(String str1, String str2) {
        if (str1 == null) {
            return str2;
        }

        if (str2 == null) {
            return str1;
        }

        int index = indexOfDifference(str1, str2);

        if (index == -1) {
            return EMPTY_STRING;
        }

        return str2.substring(index);
    }

    public static int indexOfDifference(String str1, String str2) {
        if ((str1 == null) || (str2 == null) || (str1.equals(str2))) {
            return -1;
        }

        int i;

        for (i = 0; (i < str1.length()) && (i < str2.length()); ++i) {
            if (str1.charAt(i) != str2.charAt(i)) {
                break;
            }
        }

        if ((i < str2.length()) || (i < str1.length())) {
            return i;
        }

        return -1;
    }

}

Related Exercise