Pages

Tuesday, November 16, 2021

Java String toCharArray() - How to convert string to char array?

Java String toCharArray():


The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.

Returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.


Java String toCharArray() with example - Convert string to char - Internal


Syntax:
public char[] toCharArray​()


String toCharArray() Method example:


The method toCharArray() returns an Array of chars after converting a String into sequence of characters. The returned array length is equal to the length of the String and the sequence of chars in Array matches the sequence of characters in the String.

In this example program, we are converting a String into array of chars using toCharArray() method.


package examples.java.w3schools.string;

public class StringToCharArrayExample {
 public static void main(String[] args) {

   String input = "java-w3schools";
  char[] chars = input.toCharArray();
  for (int i = 0; i < input.length(); i++) {
   System.out.print(chars[i] +" ");
  }
  
 }
}


Output:

j a v a - w 3 s c h o o l s 

This program converts input string to char array and print each character from array.


By using charat method of string, we can retrieve the each character from input string using index. 


toCharArray Internal Implementation:


This checks the whether string has Latin or UTF16 characters.
 public char[] toCharArray() {
        return isLatin1() ? StringLatin1.toChars(value) : StringUTF16.toChars(value);
        }


If string is Latin then calls StringLatin1.toChars


    public static char[] toChars(byte[] value) {
        char[] dst = new char[value.length];
        inflate(value, 0, dst, 0, value.length);
        return dst;
    }


If string is Latin then calls StringUTF16.toChars and it invokes getChars() method.


 public static char[] toChars(byte[] value) {
        char[] dst = new char[value.length >> 1];
        getChars(value, 0, dst.length, dst, 0);
        return dst;
    }

No comments:

Post a Comment

Please do not add any spam links in the comments section.