Given a string and an index, we can retrieve the character present at that specific position. Java provides several methods for accessing characters, with charAt() being the simplest and most commonly used approach.
Examples:
Input:
str = "Geeks", index = 2
Output:eInput:
str = "GeeksForGeeks", index = 5
Output:F
Different Ways to Get a Character from a String
1. Using String.charAt()
The charAt() method directly returns the char present at the specified index.
Approach:
- Take the string and the required index.
- Call str.charAt(index).
- Store or print the returned character.
public class GFG {
public static void main(String[] args) {
String str = "GeeksForGeeks";
int index = 5;
char ch = str.charAt(index);
System.out.println("Character at index " + index + " is: " + ch);
}
}
Output
Character at index 5 is: F
2. Using String.toCharArray()
The toCharArray() method converts the string into a character array. The character can then be accessed using the array index.
Approach:
- Convert the string into a char[].
- Access the character using the given index.
public class GFG {
public static void main(String[] args) {
String str = "GeeksForGeeks";
int index = 5;
char[] chars = str.toCharArray();
char ch = chars[index];
System.out.println("Character at index " + index + " is: " + ch);
}
}
Output
Character at index 5 is: F
3. Using Java Streams
The chars() method creates an IntStream of the string's UTF-16 code units. This approach is possible but is generally unnecessary when only one character is required.
import java.util.stream.*;
public class GFG {
public static void main(String[] args) {
String str = "GeeksForGeeks";
int index = 5;
char ch = (char) str.chars()
.skip(index)
.findFirst()
.orElseThrow();
System.out.println("Character at index " + index + " is: " + ch);
}
}
Output
Character at index 5 is: F
4. Using String.codePointAt()
The codePointAt() method returns the Unicode code point at the specified index. For characters represented by a single UTF-16 code unit, it can be cast to char.
public class GFG {
public static void main(String[] args) {
String str = "GeeksForGeeks";
int index = 5;
char ch = (char) str.codePointAt(index);
System.out.println("Character at index " + index + " is: " + ch);
}
}
Output
Character at index 5 is: F
Note: codePointAt() is useful when working with Unicode code points. It should not generally be described as returning an ASCII value, because Java strings support Unicode.
5. Using String.getChars()
The getChars() method can copy a specific character from the string into a character array.
public class GFG {
public static void main(String[] args) {
String str = "GeeksForGeeks";
int index = 5;
char[] chars = new char[1];
str.getChars(index, index + 1, chars, 0);
System.out.println("Character at index " + index + " is: " + chars[0]);
}
}
Output
Character at index 5 is: F