Character Extraction in Java

Character Extraction in Java

There are a few different ways by which characters can be removed from the String class object.

The string is treated as an object in Java so we can’t straightforwardly get to the characters that contain a string.

For doing this String class gives different predefined techniques.

Character Extraction in Java

charAt()

charAt() technique is utilized to separate a solitary character at a list. It has the following syntax.

Syntax

char charAt(int index)

Example:

class temp
{
	public static void main(String...s)
	{
		String str="Hello";
		char ch=str.charAt(2);
		System.out.println(ch);
	}	
}

Output:

l

In the above example, ch will contain character l. We should take care that the record ought not to be negative and ought not to surpass string length.

getChars()

It is utilized to remove more than one character. getChars() has following syntax.

void getChars(int stringStart, int stringEnd, char arr[], int arrStart)

Here stringStart and stringEnd is the beginning and closure list of the substring.

arr is the character exhibit that will contain the substring. It will contain the characters beginning from stringStart to stringEnd-1.

arrStart is the file inside arr at which substring will be duplicated. The arr cluster ought to be sufficiently huge to store the substring.

Example:

class temp
{
public static void main(String...s)
{
String str="Hello World";
char ch[]=new char[4];
str.getChars(1,5,ch,0);
System.out.println(ch);
} 
}

Output:

ello

getBytes()

getBytes() extricate characters from String object and afterwards convert the characters in a byte cluster. It has the following syntax.

byte [] getBytes()

Example:

String str="Hello";
byte b[]=str.getBytes();

toCharArray()

It is an option of getChars() technique. toCharArray() convert every one of the characters in a String object into a variety of characters.

It is the best and least demanding approach to change over the string to character exhibit. It has the following syntax.

char [] toCharArray()

Example:

class temp
{
public static void main(String...s)
{
String str="Hello World";
char ch[]=str.toCharArray();
System.out.println(ch);
} 
}

Output:

Hello World

In the event that you discovered anything incorrectly or have any questions with respect to above instructional exercise, at that point remark beneath.

Leave a Comment

error: Alert: Content is protected!!