How to separate a string when the string does not have a separator?

6

I have a String:

String texto = "1234";

String split[] = texto.split(?);

I need to separate the characters, 1-2-3-4, with each number being 1 character only.

    
asked by anonymous 28.08.2017 / 13:35

4 answers

9

Use split with regular expression looking for any character. Follow the example below

String texto = "1234";

String split[] = texto.split("(?!^)");

Result

split ["1", "2", "3", "4"]
    
28.08.2017 / 13:49
8

You can use split with regular expression as @Marquezani said, and another way to do this is to use toCharArray . See:

String texto = "1234";
char[] numbers = texto.toCharArray();

// imprimindo primeiro caracter
System.out.print("Primeiro caracter: "+numbers[0]);

Result:

  

First character: 1

See working in IDEONE .

    
28.08.2017 / 13:51
4

You can use the charAt method to separate string numbers and a loop by adding a new array:

String texto = "1234";
String[] textoSeparado = new String[texto.length()];

for(int i = 0; i < textoSeparado.length; i++){
    textoSeparado[i] = "" + texto.charAt(i);
}

See working at ideone .

    
28.08.2017 / 13:48
3

You can perform split for "none" character:

String texto = "1234";
String split[] = texto.split("");

// [0] = "1"
// [1] = "2"
// [2] = "3"
// [3] = "4"
    
28.08.2017 / 15:08