-1

How to convert a String into the String array,suppose there is a String str="name" and i want to convert into String[] which contain every element of String,i can convert into character [] but i want it in the String[]

   String[] tokens=str.toLowercase().split("?");

what should be the regex to convert it into String array so that tokens[0]="n",tokens[1]="a"

Tarun Bharti
  • 185
  • 3
  • 17

5 Answers5

2

Use direct method

char[] charArray = str.toCharArray();

and use each char

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

There's already something very similar to what you want to do built in to String. It's called toCharArray()

But, this won't do the same thing you want to do, because it will return a char[]. To convert that into a String[] you can use this:

    char[] chars = "name".toCharArray();
    String[] strings = new String[chars.length];
    for (int i = 0; i < chars.length; i++) {
        strings[i] = String.valueOf(chars[i]);
    }
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
1

If you really want to do it with a regex, you can use a non capturing group:

String name = "name";
String[] letters = name.split("(?<=.)");
System.out.println("letters = " + Arrays.toString(letters));

prints letters = [n, a, m, e]

assylias
  • 321,522
  • 82
  • 660
  • 783
0

If you want a better understanding and do it by yourself manually(although not optimal):

for (int i = 0; i < str.length())
    newChars[i] = str.charAt(i);

With newChars being of type char[]

Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
0

Convert string into char array, iterate through the array and convert each character into string and store it in string array.

ajay.patel
  • 1,957
  • 12
  • 15