Given the string str, the task is to print the middle characters of the string. If the length of the string is even, then there will be two intermediate characters, and we need to print the second intermediate character.
Examples:
Input: str = “Java” Output: v Explanation: The length of the given string is even. Therefore, there would be two middle characters ‘a’ and ‘v’, we print the second middle character. Input: str = “GeeksForGeeks” Output: o Explanation: The length of the given string is odd. Therefore, there would be only one middle character, we print that middle character.
Approach:
// Java program for the above approach class GFG { // Function that prints the middle // character of a string public static void printMiddleCharacter(String str) { // Finding string length int len = str.length(); // Finding middle index of string int middle = len / 2; // Print the middle character // of the string System.out.println(str.charAt(middle)); } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Function Call printMiddleCharacter(str); } }
Output:
o
Time Complexity: O(1)
Auxiliary Space: O(1)