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

Asked

Viewed 865 times

7

I have a string:

String texto = "1234";

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

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

  • 1

    What do you want to separate from what after all?

  • Matthew, could you explain why you want to do this ? that would help solve your problem

  • Use chartAt instead of split

  • It worked! Thank you.

4 answers

10


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

String texto = "1234";

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

Upshot

split ["1", "2", "3", "4"]

9

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

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

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

Upshot:

First character: 1

See working in IDEONE.

4

You can use the method charAt to separate the numbers of the string and a loop by adding to 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 on ideone.

3

You can perform the split by "no" character:

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

// [0] = "1"
// [1] = "2"
// [2] = "3"
// [3] = "4"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.