Java - Write code to Compare two strings, character by character, and returns the first position where the two strings differ from one another.

Requirements

Write code to Compare two strings, character by character, and returns the first position where the two strings differ from one another.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String s1 = "book2s.com";
        String s2 = "book2s.com";
        System.out.println(stringDifference(s1, s2));
    }/* w  w  w  . j a  va  2  s  .  c o m*/

    /**
     * Compares two strings, character by character, and returns the
     * first position where the two strings differ from one another.
     *
     * @param s1 The first string to compare
     * @param s2 The second string to compare
     * @return The first position where the two strings differ.
     */
    public static final int stringDifference(String s1, String s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        int len = len1 < len2 ? len1 : len2;
        for (int i = 0; i < len; i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                return i;
            }
        }
        return len;
    }
}

Related Exercise