w3resource

Java String Exercises: Check whether a substring presents in the middle of another string

Java String: Exercise-75 with Solution

Write a Java program to check whether a given substring presents in the middle of another given string. Here middle means difference between the number of characters to the left and right of the given substring not more than 1.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public boolean abcInMiddle(String stng) 
{
  String abc = "abc";
  int l = stng.length();
  int mid_pos = l / 2;
  if (l < 3)
    return false;
  if (l % 2 != 0) 
  {
    if (abc.equals(stng.substring(mid_pos-1,mid_pos+2))) 
	{
      return true;
    } else 
	{
        return false;
      }
  } 
  else if (abc.equals(stng.substring(mid_pos-1,mid_pos+2)) || abc.equals(stng.substring(mid_pos-2,mid_pos+1))) 
	  {
          return true;
  } 
  else
      return false; 
}
public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "xxabcxxx";
      System.out.println("The given string is: "+str1);
      System.out.println("Is abc appear in middle? "+m.abcInMiddle(str1));
	  }
}

Sample Output:

The given string is: xxxabcxxxxx
Is abc appear in middle? false

The given string is: xxabcxxx
Is abc appear in middle? true

Pictorial Presentation:

Java String Exercises: Check whether a substring presents in the middle of another string

Flowchart:

Flowchart: Java String Exercises - Check whether a substring presents in the middle of another string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to check whether a prefix string creates using the first specific characters in a given string, appears somewhere else in the string.
Next: Write a Java program to count how many times the substring 'life' present at anywhere in a given string.Counting can also happen for the substring 'li?e', any character instead of 'f'.

What is the difficulty level of this exercise?



Java: Tips of the Day

Count the number of occurrences of a char in a String:

int count = StringUtils.countMatches("a.b.c.d", ".");

Ref: https://bit.ly/2OTy6sG