String Methods for Character Extraction

The String class provides a number of ways in which characters can be extracted from a String object.

In this post, we will see several character extraction methods. Although the characters that comprise a string within a String object cannot be indexed as if they were a character array, many of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero.

String Character Extraction Methods

1. Extracting a Single Character

charAt(int index) 

The charAt method returns the character value at the specified index. 

String str = "JavaGuides";
char ch = str.charAt(3);
// Result: 'a'

2. Extracting a Substring

substring(int beginIndex) and substring(int beginIndex, int endIndex) 

These methods return a new string that is a substring of the original string. The beginIndex is inclusive, and the endIndex is exclusive. 

String str = "JavaGuides";
String subStr = str.substring(4, 10);
// Result: "Guides"

3. Extracting Characters into an Array

toCharArray() and getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 

The toCharArray method returns a newly allocated character array whose length is the length of the string and whose contents are initialized to contain the character sequence represented by the string. 

The getChars method copies characters from a string into the destination character array. 

String str = "JavaGuides";
char[] charArray = str.toCharArray();
// Result: ['J', 'a', 'v', 'a', 'G', 'u', 'i', 'd', 'e', 's']

char[] dst = new char[5];
str.getChars(4, 9, dst, 0);
// Result: ['G', 'u', 'i', 'd', 'e']


Character extraction is fundamental in string manipulation, and Java's String class provides methods to facilitate this process:


  1. Hi there to everybody, it’s my first go to see of this web site; this weblog consists of awesome and in fact good stuff for visitors. Hurrah, that’s what I was exploring for, what stuff! Existing here at this blog, thanks admin of this web site. You can also visit String Interview Questions for more TutorialCup. related information and knowledge.


Post a Comment

Leave Comment