Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe