Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a char array to a string array

How do you convert a char array to a string array? Or better yet, can you take a string and convert it to a string array that contains each character of the string?

Edit: thanks @Emiam! Used his code as a temp array then used another array to get rid of the extra space and it works perfectly:

String[] tempStrings = Ext.split("");
String[] mStrings = new String[Ext.length()];

for (int i = 0; i < Ext.length(); i++) 
    mStrings[i] = tempStrings[i + 1];
like image 294
Dread_99 Avatar asked Jul 12 '11 21:07

Dread_99


3 Answers

Or better yet, can you take a string and convert it to a string array that contains each character of the string?

I think this can be done by splitting the string at "". Like this:

String [] myarray = mystring.split("");

Edit: In case you don't want the leading empty string, you would use the regex: "(?!^)"

String [] mySecondArray = mystring.split("(?!^)");
like image 93
Emir Kuljanin Avatar answered Sep 22 '22 06:09

Emir Kuljanin


Beautiful Java 8 one-liner for people in the future:

String[] array = Stream.of(charArray).map(String::valueOf).toArray(String[]::new);
like image 31
Collin Alpert Avatar answered Sep 19 '22 06:09

Collin Alpert


I have made the following test to check Emiam's assumption:

public static void main(String[] args) {
    String str = "abcdef";

    String [] array = str.split("");
}

It works, but it adds an empty string in position 0 of the array. So array is 7 characters long and is { "", "a", "b", "c", "d", "e", "f" }.

I have made this test with Java SE 1.6.

like image 33
Shlublu Avatar answered Sep 19 '22 06:09

Shlublu