write a java program to Fetch Middle Characters from String.

Write a program to read a string of even length and to fetch two middlemost characters from the input string and return it as string output.

Include a class UserMainCode with a static method getMiddleChars which accepts a string of even length as input. The return type is a string which should be the middle characters of the string.

Create a class Main which would get the input as a string and call the static method getMiddleCharspresent in the UserMainCode.

Input and Output Format:

Input consists of a string of even length.

The output is a string.

Refer sample output for formatting specifications.

 

Sample Input 1:

this

Sample Output 1:

hi
Sample Input 1:

Hell

Sample Output 1:

el

Fetch Middle Characters from String in Java.

import java.util.Scanner;


public class Main4 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    
    String s1 = UserMainCode.getMiddleChars(s);
    System.out.println(s1);
  }
}

 class UserMainCode {
    public static String getMiddleChars(String str)
    {
                StringBuffer sb=new StringBuffer();
                 if(str.length()%2==0)
                 {
                 sb.append(str.substring((str.length()/2)-1,(str.length()/2)+1));
                 }
                 return sb.toString();
                 }
    }

Add a Comment

Your email address will not be published. Required fields are marked *

nine + 13 =