Converting String to "Character" array in Java

Go To StackoverFlow.com

95

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?

2012-04-04 06:46
by kgd
What do you mean by "doesn't fit with the character array" - barsju 2012-04-04 06:47
Can you re-word this or articulate a bit more, or perhaps provide a code example - blackcompe 2012-04-04 06:50
To convert char to Character, use Character.valueOf(mychar). If it is an array, loop each element and convert - ee. 2012-04-04 06:50
java needs a map function, lambda expressions - Eric Hartford 2013-05-21 21:37


164

Use this:

String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
2012-04-04 06:52
by Kuldeep Jain
I wish ArrayUtils is standard in JVMs - Alvin 2012-04-04 06:58
ArrayUtils is from commons-lang, not JDK, right - Eric Wang 2019-02-21 14:56


47

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()
2014-12-29 14:47
by Alexis C.


32

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++) {
      array[i] = new Character(s.charAt(i));
   }

   return array;
}
2012-04-04 06:51
by Alvin
+1 for Character[] array = new Characer[s.length()] - Ankit 2012-10-21 10:33
Too many Character Objects will be instantiated if its a huge String - realPK 2016-06-27 08:19
Why not write a little method yourself? Because a method already exists (toCharArray()), and the method that already exists has far more engineers devoted to and interested in guaranteeing the performance and reliability of that function, than what may be copied/pasted from a stackoverflow post - HoldOffHunger 2016-09-24 23:00
@HoldOffHunger You are absolutely right. However toCharArray() returns primitive type of array instead of Character object as need by OP. Sure, you can loop through the char[] again to convert it to Character[]. But, looping through a string ad creating Character object is so simple I don't see why not just roll your own if you don't want to bring in third party library - Alvin 2016-09-26 21:38


5

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
2012-04-04 07:18
by xxxxxxxx d
This is not at all what the OP was asking for - Qix 2014-11-04 02:54


2

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].

2012-04-04 06:51
by Chandra Sekhar


2

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[]).

2012-04-04 06:55
by Sandro


2

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;
}
2014-05-08 04:49
by loknath


1

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]);
    }
2012-04-04 06:56
by Balaswamy Vaddeman


0

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]);
2013-10-28 01:34
by M.Shams Tabrez


0

chaining is always best :D

String str = "somethingPutHere";
Character[] c = ArrayUtils.toObject(str.toCharArray());
2013-12-18 21:18
by ak_2050
chaining is always best False - Qix 2014-11-04 02:55
ArrayUtils is not part of the JDK - mbmast 2016-11-30 06:03


0

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;
}
2016-06-27 08:24
by realPK


0

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
2016-08-29 15:43
by TheBro21
Ads