Java String Character Extraction


The String category provides a variety of the way within which characters will be extracted from a String object.

charAt()

To extract a single character from a String, you can refer directly to an individual character via the charAt() method.

Program
public class Main
{
	public static void main(String[] args) 
	{
	   String s = "guriasoft";
	   char ch = s.charAt(2);
	   System.out.println(ch);
	}
}
Run

getChars()

If you wish to extract over one character at a time, you'll be able to use the getChars() technique.

Program
public class Main
{
	public static void main(String[] args) 
	{
	   String s = "I am a good boy";
	   int start = 7;
	   int end = 11;
	   char c[] = new char[end-start];
	   s.getChars(start,end,c,0);
	   System.out.println(c);
	}
}
Run

getBytes()

There is an alternative to getChars() that stores the characters in an array of bytes. This method is called getBytes(), and it uses the default character-to-byte conversions provided by the platform.

Program
public class Main
{
	public static void main(String[] args) 
	{
	   String s = "abc";
	   byte b[]=s.getBytes();
	   for(byte c : b)
	   {
	       System.out.println(c);
	   }
	}
}
Run

toCharArray()

If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray() method. It returns an array of characters for the whole string.

Program
public class Main
{
	public static void main(String[] args) 
	{
	   String s = "abc";
	   char c[] = s.toCharArray();
	   for(char d : c)
	   {
	       System.out.println(d);
	   }
	}
}
Run