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

Requirements

Write code to Compares 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 = "ook2s.com";
        String s2 = "book2s.com";
        System.out.println(stringDifference(s1, s2));
    }/*from   w ww .  j  a v a 2  s.  co  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