String, Substring
string substring

Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So “xxcaazz” and “xxbaaz” yields 3, since the “xx”, “aa”, and “az” substrings appear in the same place in both strings.

stringMatch(“xxcaazz”, “xxbaaz”) → 3 stringMatch(“abc”, “abc”) → 2 stringMatch(“abc”, “axc”) → 0

PROGRAM CODE:
public class java5
{
    public static intstringMatch(String str1, String str2)
    {
        String s1, s2;
        intcnt = 0;
        for(inti = 0; i< (str1.length()) - 1; i++)
        {
            if(i< (str1.length()) - 2)
            {
                s1 = str1.substring(i, i + 2);
                s2 = str2.substring(i, i + 2);
            }
            else
            {
                s1 = str1.substring(i);
                s2 = str2.substring(i);
            }
            //System.out.println(s1 + "\t" + s2);
            if(s1.equals(s2))
                cnt++;
        }
        return cnt;
    }

    public static void main(String[] args)
    {
        System.out.println(stringMatch("xxcaazz", "xxbaaz"));
        System.out.println(stringMatch("abc", "abc"));
        System.out.println(stringMatch("abc", "axc"));
    }
}        

Output:

3
2
0

LEAVE A REPLY

Please enter your comment!
Please enter your name here