Two strings having same sub string Program
string prrogram to find the substring from strings from the two given strings. if two consecutive letters are same they'll displayed. and the count will print.
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
public class java5
{
public static int stringMatch(String str1, String str2)
{
String s1, s2;
int cnt = 0;
int len = Math.min(str1.length(), str2.length());
for(int i = 0; i < len - 1; i++)
{
s1 = str1.substring(i, i + 2);
s2 = str2.substring(i, i + 2);
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
Related Posts
Continue learning with these related articles
Sum of First n Natural Numbers in Java (Loop and Formula)
Find the sum of the first n natural numbers in Java with a for loop, a while loop and the formula n(n + 1)/2, with a dry run and the sums of even numbers, odd numbers, squares and cubes.
Prime Number Program in Java: Check a Number and Print Primes in a Range
Check whether a number is prime in Java by counting its factors, a faster square-root method with isPrime(), and a program that prints all prime numbers in a range.

Encapsulation, Access Specifiers and Scope of Variables in Java for ICSE Class 10
ICSE Class 10 Computer Applications notes on encapsulation: private, default, protected and public access, data hiding with getter and setter methods, instance vs static (class) variables, local variables and scope, with a solved BankAccount program.