Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character.
Input: str = “Java”
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”
The length of the given string is odd.
Therefore, there would be only one middle character, we print that middle character.
- Get the string whose middle character is to be found.
- Calculate the length of the given string.
- Finding the middle index of the string.
- Now, print the middle character of the string at index middle using function charAt() in Java.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.