[java] Converting String to "Character" array in Java

I want to convert a String to an array of objects of Character class but I am unable to perform the conversion. I know that I can convert a String to an array of primitive datatype type "char" with the toCharArray() method but it doesn't help in converting a String to an array of objects of Character type.

How would I go about doing so?

This question is related to java arrays string character

The answer is


if you are working with JTextField then it can be helpfull..

public JTextField display;
String number=e.getActionCommand();

display.setText(display.getText()+number);

ch=number.toCharArray();
for( int i=0; i<ch.length; i++)
    System.out.println("in array a1= "+ch[i]);

I hope the code below will help you.

String s="Welcome to Java Programming";
char arr[]=s.toCharArray();
for(int i=0;i<arr.length;i++){
    System.out.println("Data at ["+i+"]="+arr[i]);
}

It's working and the output is:

Data at [0]=W
Data at [1]=e
Data at [2]=l
Data at [3]=c
Data at [4]=o
Data at [5]=m
Data at [6]=e
Data at [7]= 
Data at [8]=t
Data at [9]=o
Data at [10]= 
Data at [11]=J
Data at [12]=a
Data at [13]=v
Data at [14]=a
Data at [15]= 
Data at [16]=P
Data at [17]=r
Data at [18]=o
Data at [19]=g
Data at [20]=r
Data at [21]=a
Data at [22]=m
Data at [23]=m
Data at [24]=i
Data at [25]=n
Data at [26]=g

One liner with :

String str = "testString";

//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray = 
    str.chars().mapToObj(c -> (char)c).toArray(Character[]::new); 

What it does is:

  • get an IntStream of the characters (you may want to also look at codePoints())
  • map each 'character' value to Character (you need to cast to actually say that its really a char, and then Java will box it automatically to Character)
  • get the resulting array by calling toArray()

If you don't want to rely on third party API's, here is a working code for JDK7 or below. I am not instantiating temporary Character Objects as done by other solutions above. foreach loops are more readable, see yourself :)

public static Character[] convertStringToCharacterArray(String str) {
    if (str == null || str.isEmpty()) {
        return null;
    }
    char[] c = str.toCharArray();
    final int len = c.length;
    int counter = 0;
    final Character[] result = new Character[len];
    while (len > counter) {
        for (char ch : c) {
            result[counter++] = ch;
        }
    }
    return result;
}

chaining is always best :D

String str = "somethingPutHere";
Character[] c = ArrayUtils.toObject(str.toCharArray());

I used the StringReader class in java.io. One of it's functions read(char[] cbuf) reads a string's contents into an array.

String str = "hello";
char[] array = new char[str.length()];
StringReader read = new StringReader(str);

try {
    read.read(array); //Reads string into the array. Throws IOException
} catch (IOException e) {
    e.printStackTrace();
}

for (int i = 0; i < str.length(); i++) {
        System.out.println("array["+i+"] = "+array[i]);
}

Running this gives you the output:

array[0] = h
array[1] = e
array[2] = l
array[3] = l
array[4] = o

Why not write a little method yourself

public Character[] toCharacterArray( String s ) {

   if ( s == null ) {
     return null;
   }

   int len = s.length();
   Character[] array = new Character[len];
   for (int i = 0; i < len ; i++) {
      /* 
      Character(char) is deprecated since Java SE 9 & JDK 9
      Link: https://docs.oracle.com/javase/9/docs/api/java/lang/Character.html
      array[i] = new Character(s.charAt(i));
      */
      array[i] = s.charAt(i);
   }

   return array;
}

another way to do it.

String str="I am a good boy";
    char[] chars=str.toCharArray();

    Character[] characters=new Character[chars.length];
    for (int i = 0; i < chars.length; i++) {
        characters[i]=chars[i];
        System.out.println(chars[i]);
    }

String#toCharArray returns an array of char, what you have is an array of Character. In most cases it doesn't matter if you use char or Character as there is autoboxing. The problem in your case is that arrays are not autoboxed, I suggest you use an array of char (char[]).


You have to write your own method in this case. Use a loop and get each character using charAt(i) and set it to your Character[] array using arrayname[i] = string.charAt[i].


Converting String to Character Array and then Converting Character array back to String

   //Givent String
   String given = "asdcbsdcagfsdbgdfanfghbsfdab";

   //Converting String to Character Array(It's an inbuild method of a String)
   char[] characterArray = given.toCharArray();
   //returns = [a, s, d, c, b, s, d, c, a, g, f, s, d, b, g, d, f, a, n, f, g, h, b, s, f, d, a, b]

//ONE WAY : Converting back Character array to String

  int length = Arrays.toString(characterArray).replaceAll("[, ]","").length();

  //First Way to get the string back
  Arrays.toString(characterArray).replaceAll("[, ]","").substring(1,length-1)
  //returns asdcbsdcagfsdbgdfanfghbsfdab
  or 
  // Second way to get the string back
  Arrays.toString(characterArray).replaceAll("[, ]","").replace("[","").replace("]",""))
 //returns asdcbsdcagfsdbgdfanfghbsfdab

//Second WAY : Converting back Character array to String

String.valueOf(characterArray);

//Third WAY : Converting back Character array to String

Arrays.stream(characterArray)
           .mapToObj(i -> (char)i)
           .collect(Collectors.joining());

Converting string to Character Array

Character[] charObjectArray =
                           givenString.chars().
                               mapToObj(c -> (char)c).
                               toArray(Character[]::new);

Converting char array to Character Array

 String givenString = "MyNameIsArpan";
char[] givenchararray = givenString.toCharArray();


     String.valueOf(givenchararray).chars().mapToObj(c -> 
                         (char)c).toArray(Character[]::new);

benefits of Converting char Array to Character Array you can use the Arrays.stream funtion to get the sub array

String subStringFromCharacterArray = 

              Arrays.stream(charObjectArray,2,6).
                          map(String::valueOf).
                          collect(Collectors.joining());

This method take String as a argument and return the Character Array

/**
 * @param sourceString
 *            :String as argument
 * @return CharcterArray
 */
public static Character[] toCharacterArray(String sourceString) {
    char[] charArrays = new char[sourceString.length()];
    charArrays = sourceString.toCharArray();
    Character[] characterArray = new Character[charArrays.length];
    for (int i = 0; i < charArrays.length; i++) {
        characterArray[i] = charArrays[i];
    }
    return characterArray;
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to character

Set the maximum character length of a UITextField in Swift Max length UITextField Remove last character from string. Swift language Get nth character of a string in Swift programming language How many characters can you store with 1 byte? How to convert integers to characters in C? Converting characters to integers in Java How to check the first character in a string in Bash or UNIX shell? Invisible characters - ASCII How to delete Certain Characters in a excel 2010 cell