﻿ Java exercises: Check whether a string 'abc' in the middle of a given string - w3resource

# Java String Exercises: Check whether a string 'abc' in the middle of a given string

## Java String: Exercise-75 with Solution

Write a Java program to check whether a string 'abc' in the middle of a given string. Here middle means the number of character to the left and right of the substring 'abc' must differ by at most one.

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: Flowchart: Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

﻿

Inviting useful, relevant, well-written and unique guest posts