In Java,The Easy way to convert simple String to Char Array. Question How to convert String to Char Array in Java? and how to iterate through an arraylist in java?
Sometimes I have to convert data String to the char array in java programs as well as convert a data string to char from each array index.
Java: Simple way to convert String to Char Array
Given a below text a string, the program is to convert this data string into a character array in Java.
- Phase 1: Fetch the string.
- Phase 2: Make a character array of the all the length as of data string.
- Phase 3: range over the data string to copy all the character at the n’th index of string to n’th last index in the Your array.
- Phase 4: and last Return or execute the operation on the data character array.
Also you can read my prev Article for Paypal Payment Gateway Integration using Java
3 methods related to char in String Class
char[] toCharArray(): char charAt(int index) getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
Java Source Code:
package com.pakainfo; /** * @author Pakainfo.com */ public class PakainfoStringToCharArray { public static void main(String[] args) { String userDataString = "Welcome To Pakainfo"; char[] stringToCharArray = userDataString.toCharArray(); for (char output : stringToCharArray) { System.out.println(output); } } }
Output:
W e l c o m e T 0 P a k a i n f o
Using Naive Approach
Java program to Convert a String to a Character array using Naive Approach
Examples: Input: Welcome To Pakainfo Output: [W, e, l, c, o, m, e, , T, o, , P, a, k, a, i, n, f, o] Input: PakainfoCom Output: [P, a, k, a, i, n, f, o, C, o, m]
// Java Example to Convert a String // to a Character array using Naive Approach import java.util.*; public class Pakainfo { public static void main(String args[]) { String userDataString = "PakainfoCom"; // Making array of string length char[] ch = new char[userDataString.length()]; // Copy character by character into array for (int i = 0; i < userDataString.length(); i++) { ch[i] = userDataString.charAt(i); } // displaying content of array for (char c : ch) { System.out.println(c); } } }
Output:
P a k a i n f o C o m
Web Programming Tutorials Example with Demo
Read :
Summary
You can also read about AngularJS, ASP.NET, VueJs, PHP.
I hope you get an idea about String to char array java – convert string to char.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.