Get char array from string

ReturnMethodSummary
static StringcopyValueOf(char[] data)Returns a String that represents the character sequence in the array specified.
static StringcopyValueOf(char[] data, int offset, int count)Returns a String that represents the character sequence in the array specified.
voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters from this string into the destination character array.
char[]toCharArray()Converts this string to a new character array.

public class Main {
  public static void main(String[] argv) {
    char[] chars = new char[] { 'j', 'a', 'v', 'a', '2', 's', '.', 'c', 'o','m' };

    System.out.println(String.copyValueOf(chars));
  }
}

The output:


java2s.com

import java.util.Arrays;

public class Main {
  public static void main(String[] argv) {
    String str = "java2s.com";
    char[] chars = str.toCharArray();
    System.out.println(Arrays.toString(chars));
  }
}

The output:


[j, a, v, a, 2, s, ., c, o, m]

To extract more than one character, use the getChars( ) method.

The following program demonstrates getChars( ). It gets a sub set of the chars.

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

    String s = "This is a test string from java2s.com.";
    int start = 10;
    int end = 14;
    char buf[] = new char[end - start];

    s.getChars(start, end, buf, 0);
    System.out.println(buf);
  }
}

Here is the output of this program:


test
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.