Share on Google+Share on Google+

Java get middle character

Advertisement
In this tutorial, you will learn how to get middle character from the word.

Java get middle character

In this tutorial, you will learn how to get middle character from the word. Here is an example of getting the middle letter of the word entered by the user using Java. If you have a word string 'company' and you want to get the character 'p' from the word, then you can use the below code.

Example:

import java.util.*;

class GetMiddleCharacter
{
	public static void main(String[] args) 
	{
		Scanner input=new Scanner(System.in);
		System.out.print("Enter word: ");
		String str=input.nextLine();
		int len=str.length();
		int c=len/2;
		char ch[]=str.toCharArray();
		System.out.println("Middle Character is: "+ch[c]);
	}
}

Output:

Enter word: company
Middle Character is: p

Advertisements

Posted on: December 12, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.