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.
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
- charAt()
- getChars()
- getBytes()
- toCharArray()
charAt(int index)
To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method.
Example 1: Returns the char value at the specified index of this string. The first char value is at index 0.
String str = "Welcome to string handling guide";
char ch1 = str.charAt(0);
char ch2 = str.charAt(5);
char ch3 = str.charAt(11);
char ch4 = str.charAt(20);
System.out.println("Character at 0 index is: " + ch1);
System.out.println("Character at 5th index is: " + ch2);
System.out.println("Character at 11th index is: " + ch3);
System.out.println("Character at 20th index is: " + ch4);
Output:
Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n
Example 2: Throws IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
String str = "Java Guides";
char ch1 = str.charAt(str.length() + 1);
System.out.println("character :: " + ch1);
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12
at java.lang.String.charAt(String.java:658)
at com.javaguides.strings.methods.ChatAtExample.charAtExample2(ChatAtExample.java:26)
at com.javaguides.strings.methods.ChatAtExample.main(ChatAtExample.java:6)
Example 3: How to get the first and last character of the string
String str = "Java Guides";
int strLength = str.length();
// Fetching first character
System.out.println("Character at 0 index is: " + str.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + str.charAt(strLength - 1));
Output;
Character at 0 index is: J
Character at last index is: s
getChars()
If you need to extract more than one character at a time, you can use the getChars( ) method.
It has this general form:
It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd–1.
The array that will receive the characters is specified by target. The index within the target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.
The array that will receive the characters is specified by target. The index within the target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.
The following program demonstrates the usage of getChars() method:
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
Here is the output of this program:
demo
getBytes()
There are four versions of getBytes() methods. There is an alternative to getChars( ) that stores the characters in an array of bytes.
byte[] getBytes() - Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes() - Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes(Charset charset) - Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) - Deprecated.
byte[] getBytes(String charsetName) - Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
Let's write an example to demonstrate all the getBytes() methods.
public class GetBytesExamples { public static void main(String[] args) throws UnsupportedEncodingException { String str = "javaguides"; // Encodes this String into a sequence of bytes using the platform's // default charset, storing the result into a new byte array. byte[] bs = str.getBytes(); for (byte b: bs) { System.out.println(b); } // Encodes this String into a sequence of bytes using the given charset, // storing the result into a new byte array. byte[] bs1 = str.getBytes(Charset.forName("UTF-8")); for (byte b: bs1) { System.out.println(b); } // Encodes this String into a sequence of bytes using the given charset, // storing the result into a new byte array. byte[] bs2 = str.getBytes("UTF-8"); for (byte b: bs2) { System.out.println(b); } byte[] dest = new byte[str.length()]; str.getBytes(0, str.length(), dest, 0); for (byte b: dest) { System.out.println(b); } } }
toCharArray()
This method converts this string to a new character array.
Example: This is a complete example to demonstrate the usage of the toCharArray() method.
public class ToCharArrayExample {
public static void main(String[] args) {
String str = "javaguides";
char[] characters = str.toCharArray();
for (char c : characters) {
System.out.println(c);
}
}
}
Output:
j
a
v
a
g
u
i
d
e
s
GitHub Repository
Reference
Strings Related Posts
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course