0

There is a String value Eg:('12560') and I need to put it into an array by index wise.

Eg : Input:

String x = "12560";

Output:

String arr[] = {"1","2","5","6","0"};
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • 1
    Downvoted because no attempt whatsoever to solve it yourself or to do any research. You are expected to do that before posting on SO, please see [ask], thanks. – Zabuzard Mar 29 '20 at 18:46

4 Answers4

2

Here's a one line answer:

JAVA 8 and above:

x.split("");

JAVA 7 and below:

x.split("(?!^)");
Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35
1

This should do the job:

String x = "12560"
char[] chars = x.toCharArray();
TacheDeChoco
  • 3,683
  • 1
  • 14
  • 17
0

Something like this shall work.

Create a new String [] array, proceed with adding each character as a new string inside it.

     String x = "12560";

      String output [] = new String[x.length()];
      for(int i = 0 ; i < x.length() ; i++){
          output[i] = x.charAt(i)+"";
          System.out.println(output[i]);
      }

Output -

1
2
5
6
0
RRIL97
  • 858
  • 4
  • 9
-1

This code is worked for me.

    //c is the user input value
    String c  = "12560";
    //create a String array to add final results
    String finArr[] = new String[c.split("").length];
    //put input value to an array by splitting
    String arr[] = c.split("");
    //add
    for(int i=0;i<arr.length;i++){
        finArr[i] = arr[i];
    }
    for(int j=0;j<finArr.length;j++){
        System.out.println(finArr[j]);
    }
  • 1
    The "add-loop" is completely uncessary. The data is already in `arr`. Also, you are executing the split twice, once to get the length, once to get the data. But one execution is enough. Additionally, you should not go for a c-style array notation `Foo foo[]` but for Java-like `Foo[] foo` notation. – Zabuzard Mar 29 '20 at 18:49