Print the middle character of a string
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.
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:
- 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:
C++
#include<bits/stdc++.h>
using namespace std;
void printMiddleCharacter(string str)
{
int len = str.size();
int middle = len / 2;
cout << str[middle];
}
int main()
{
string str = "GeeksForGeeks" ;
printMiddleCharacter(str);
return 0;
}
|
Java
class GFG {
public static void
printMiddleCharacter(String str)
{
int len = str.length();
int middle = len / 2 ;
System.out.println(str.charAt(middle));
}
public static void
main(String args[])
{
String str = "GeeksForGeeks" ;
printMiddleCharacter(str);
}
}
|
Python3
def printMiddleCharacter( str ):
length = len ( str );
middle = length / / 2 ;
print ( str [middle]);
str = "GeeksForGeeks" ;
printMiddleCharacter( str );
|
C#
using System;
class GFG{
public static void printMiddlechar(String str)
{
int len = str.Length;
int middle = len / 2;
Console.WriteLine(str[middle]);
}
public static void Main(String []args)
{
String str = "GeeksForGeeks" ;
printMiddlechar(str);
}
}
|
Javascript
<script>
function printMiddleCharacter(str)
{
let len = str.length;
let middle = parseInt(len / 2, 10);
document.write(str[middle]);
}
let str = "GeeksForGeeks" ;
printMiddleCharacter(str);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
10 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...