Here we are converting a string into a primitive datatype. It is recommended to have good knowledge of Wrapper classes and concepts like autoboxing and unboxing as in java they are frequently used in converting data types.
Illustrations:
Input : Hello World
Output : [H, e, l, l, o, W, o, r, l, d]
Input : GeeksForGeeks
Output : [G, e, e, k, s, F, o, r, G, e, e, k, s]
Different Ways of Converting a String to Character Array
- Using a naive approach via loops
- Using toChar() method of String class
Way 1: Using a Naive Approach
- Get the string.
- Create a character array of the same length as of string.
- Traverse over the string to copy character at the i’th index of string to i’th index in the array.
- Return or perform the operation on the character array.
Example:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
String str = "GeeksForGeeks" ;
char [] ch = new char [str.length()];
for ( int i = 0 ; i < str.length(); i++) {
ch[i] = str.charAt(i);
}
for ( char c : ch) {
System.out.println(c);
}
}
}
|
Output
G
e
e
k
s
F
o
r
G
e
e
k
s
Tip: This method acts very important as in most interviews an approach is seen mostly laid through via this method.
Procedure:
- Getting the string.
- Creating a character array of the same length as of string.
- Storing the array return by toCharArray() method.
- Returning or performing an operation on a character array.
Example:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
String str = "GeeksForGeeks" ;
char [] ch = str.toCharArray();
for ( char c : ch) {
System.out.println(c);
}
}
}
|
Output
G
e
e
k
s
F
o
r
G
e
e
k
s
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
03 Apr, 2023
Like Article
Save Article