Java String to char Example
String
to char conversion is a very simple procedure in Java. This process is useful when we want to use char format instead of strings in our applications, for instance in the arguments in command line.
In this example we are going to show you how to parse a String
to character(s).
1. Example of String to char conversion
Create a new java file with the name StringToCharClass
and paste the following code.
StringToCharClass.java:
package com.javacodegeeks.basics.stringtochar; import java.util.Arrays; public class StringToCharClass { public static void main(String[] args) { String mystr = "JCG Examples"; char[] charArray = mystr.toCharArray(); System.out.println("mystr in character array: " + Arrays.toString(charArray)); // handle the char array for(int i = 0; i < charArray.length; i++) { System.out.print(charArray[i] + " - "); } // take a char (letter) in a specific position char firstLetter = mystr.charAt(0); System.out.println("\nFirst letter of mystr: " + firstLetter); // take every char of the string for(int i = 0; i < mystr.length(); i++) { System.out.println("Char " + mystr.charAt(i) + " in position " + i); } } }
Now lets explain the code above. We can convert a String
to an array of characters, with the use of toCharArray()
operation. So, the resulting array includes one char of the specified string in each position. In order to handle the values of the array we can use a for-loop, but for printing the array in a readable way, we can simply call Arrays.toString()
method.
To get a char in a particular position of the string, we can use charAt()
function by defining the specified index. As you can imagine, charAt()
can be called into a for-loop, in order to get all the chars of the string. In the example you can notice that we use that for-loop, where the index reaches the length of the string.
Now you can see the results of the execution of the source code.
Output:
mystr in character array: [J, C, G, , E, x, a, m, p, l, e, s] J - C - G - - E - x - a - m - p - l - e - s - First letter of mystr: J Char J in position 0 Char C in position 1 Char G in position 2 Char in position 3 Char E in position 4 Char x in position 5 Char a in position 6 Char m in position 7 Char p in position 8 Char l in position 9 Char e in position 10 Char s in position 11
Download the source code
This was an example of string to char in Java. Download the source code of this example: StringToCharExample.zip