w3resource
Java Programming Exercies

Java String Exercises: Return the number of index positions from two given strings where they contain the same substring of two characters

Java String: Exercise-98 with Solution

Write a Java program to return the number of index positions from two given strings where they contain the same substring of two characters.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public int noOfMatchPosition(String stng_a, String stng_b) 
{
  int l = Math.min(stng_a.length(), stng_b.length());
  int ctr = 0;
  for (int i = 0; i < l-1; i++)
  {
    String str_a = stng_a.substring(i, i+2);
    String str_b = stng_b.substring(i, i+2);
    if (str_a.equals(str_b))
      ctr
	  ++; 
  }
  return ctr;
}

public static void main (String[] args)
    {
      Main m= new Main();
      String str1 = "aabxyyz";
	  String str2 = "aabuyyz";
      System.out.println("The given strings are: "+str1+"  and "+str2);
      System.out.println("The sum of the digits in the string is: "+m.noOfMatchPosition(str1,str2));
	  }
}

Sample Output:

The given strings are: aabxyyz  and aabuyyz
The sum of the digits in the string is: 4

Flowchart:

Flowchart: Java String Exercises - Return the number of index positions from two given strings where they contain the same substring of two characters

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to return a string with the characters of the index position 0,1,2, 5,6,7, ... from a given string.
Next: Write a Java program to check whether the first instance of 'z' is immediately followed by another 'z' in a given string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming