-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"

0

5 Answers 5

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]);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

thanks sir for your ans but,how we can achieve this through regex?
2

Use direct method

char[] charArray = str.toCharArray();

and use each char

1 Comment

i want String[] not char[]
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]

Comments

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.