The simplest way to convert String to Char Array. How to convert String to Char Array in Java?
There are two different ways
to covert String() to Char[] in Java:
- Using string.toCharArray() Method
- Using standard approach. Iterate through String and add to chat Array.
Here is a Java code:
Create Java class CrunchifyStringToCharArray.java
. Put below code into a file.
package crunchify.com.tutorials; /** * @author Crunchify.com * In Java how to convert String to Char Array? (Two ways) - String() to Char[] */ public class CrunchifyStringToCharArray { public static void main(String[] args) { // Method-1: using string.toCharArray() String crunchifyString = "This is Crunchify"; // toCharArray() converts this string to a new character array. char[] crunchifyCharArray = crunchifyString.toCharArray(); crunchifyPrint("=========== Method-1: using string.toCharArray()"); for (char crunchifyResult1 : crunchifyCharArray) { crunchifyPrint(crunchifyResult1 + ""); } // Method-2: Iterate through the string to copy character String crunchifyString2 = "Crunchify.com"; crunchifyPrint("\n=========== Method-2: Standard way: Iterate through the String to copy character"); char[] crunchifyCharArray2 = new char[crunchifyString2.length()]; for (int counter = 0; counter < crunchifyString2.length(); counter++) { // charAt() returns the char value at the specified index. An index ranges from 0 to length() - 1. crunchifyCharArray2[counter] = crunchifyString2.charAt(counter); } for (char newCh : crunchifyCharArray2) { crunchifyPrint(newCh + ""); } } private static void crunchifyPrint(String string) { System.out.println(string); } }
Eclipse Console Result:
Just run above program in Eclipse or IntelliJ IDEA and you should see result like below.
=========== Method-1: using string.toCharArray() T h i s I s C r u n c h i f y =========== Method-2: Iterate through the string to copy character C r u n c h i f y . c o m Process finished with exit code 0
Let me know if you face any issue running above program and get any Java Exception.
The post In Java how to convert String to Char Array? (Two ways) – String() to Char[] appeared first on Crunchify.
0 Commentaires