charAt()
charAt() method is used to extract a single character at an index. It has following syntax.
Syntax
1
|
char charAt(int index)
|
Example
1
2
3
4
5
6
7
8
9
|
class temp
{
public static void main(String...s)
{
String str="Hello";
char ch=str.charAt(2);
System.out.println(ch);
}
}
|
Output
l
In above example ch will contain character l. We must take care that the index should not be negative and should not exceed string length.
getChars()
It is used to extract more than one character. getChars() has following syntax.
Syntax
1
|
void getChars(int stringStart, int stringEnd, char arr[], int arrStart)
|
Here stringStart and stringEnd is the starting and ending index of the substring. arr is the character array that will contain the substring. It will contain the characters starting from stringStart to stringEnd-1. arrStart is the index inside arr at which substring will be copied. The arr array should be large enough to store the substring.
Example
1
2
3
4
5
6
7
8
9
10
|
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() extract characters from String object and then convert the characters in a byte array. It has following syntax.
Syntax
1
|
byte [] getBytes()
|
Example
1
2
|
String str="Hello";
byte b[]=str.getBytes();
|
toCharArray()
It is an alternative of getChars() method. toCharArray() convert all the characters in a String object into an array of characters. It is the best and easiest way to convert string to character array. It has following syntax.
Syntax
1
|
char [] toCharArray()
|
Example
1
2
3
4
5
6
7
8
9
|
class temp
{
public static void main(String...s)
{
String str="Hello World";
char ch[]=str.toCharArray();
System.out.println(ch);
}
}
|
Output
Hello World
No comments:
Post a Comment