Java - Write code to Return the number of characters in the two Strings that are the same.

Requirements

Write code to Return the number of characters in the two Strings that are the same.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str1 = "book2s.com";
        String str2 = "book2s.com";
        System.out.println(difference(str1, str2));
    }/*from w w  w  .  ja va2 s  .co  m*/

    /**
     * Returns the number of characters in the two Strings that are the same.
     * 
     * @param str1 a String.
     * @param str2 a String.
     * @return The number of characters in the two Strings that are the same.
     * 
     */
    public static int difference(String str1, String str2) {
        if (str1 == null || str2 == null) {
            return 0;
        }
        int lengthToMatch = Math.min(str1.length(), str2.length());
        int diff = 0;
        for (int i = 0; i < lengthToMatch; i++) {
            if (str1.charAt(i) == str2.charAt(i)) {
                diff++;
            }
        }
        return diff;
    }
}