Home > Back-end >  how to convert a string into an array of characters - java 8
how to convert a string into an array of characters - java 8

Time:07-08

Passed in string: hello

populate arrayA[] with: ["h", "e", "l", "l", "o"];

Without using any packages or imports

    int size = a.length();
    
    String arrayA[] = new String[size];
    
    for(int i = 0; i<size; i  ){
    //pass each index in the string to arrayA
    }

CodePudding user response:

I believe this could be solved using

String[] fooArr = foo.split("");

Will need to circle back if it is preinstalled in Java 8 or no introduced until a later package.

CodePudding user response:

Here's a solution that:

  • works with ASCII characters (probably has issues with Unicode)
  • doesn't use any imports – except for java.util.Arrays so that it can print out the character array for verification, but that's only for this answer, doesn't have anything to do with the code solution itself.
  • builds an array of characters (char), and not java.lang.String as you posted in your code – your expected output ["h", "e", "l", "l", "o"] could be an array of Strings (double-quotes) but also looks like it would work as characters
import java.util.Arrays;

String s = "hello";
char[] chars = new char[s.length()];
for (int i = 0; i < s.length(); i  ) {
    chars[i] = s.charAt(i);
}
System.out.println("chars[]: "   Arrays.toString(chars));

Here's the output:

chars[]: [h, e, l, l, o]

CodePudding user response:

This can be done using toCharArray().

String foo = "example";

char[] fooChars = foo.toCharArray();

If you actually want a string array for each character you can simply use .toString().

String[] fooChars = new String[foo.length()];
    
for(int i = 0; i < foo.length(); i  ){
    fooChars[i] = foo.charAt(i).toString();
}
  • Related