How to split a string every 2 characters?

6

I'm trying to split a string every two characters, but I do not have a delimiter and need to use the entire string.

Example:

String exemplo= 99E65A78

String ex1= 99
String ex2= E6
String ex3= 5A
String ex4= 78
    
asked by anonymous 22.11.2017 / 12:38

4 answers

1

Try this:

System.out.println(Arrays.toString(
    "8S8Q4D1SKCQC2C4S6H4C6DJS2S1C6C".split("(?<=\G.{2})")
));
    
22.11.2017 / 12:51
6

I would do so:

import java.util.*;

public class Program {
    public static void main (String[] args) {
        String texto = "99E65A78";
        List<String> partes = new ArrayList<String>();
        for (int i = 0; i < texto.length(); i += 2) partes.add(texto.substring(i, Math.min(i + 2,texto.length())));
        for (int i = 0; i < partes.size(); i++) System.out.println(partes.get(i));
    }
}

See working on ideone . And no Coding Ground . Also I placed GitHub for future reference .

I'm jumping every 2 characters and saving in a list. I'm just careful not to get a character smaller than the size.

The second loop is just for show.

There are other ways to do it, but this must be the most performative and it's very simple.

    
22.11.2017 / 12:54
3

Another way would be to use a while :

String text = "99E65A78"
List<String> stringSerparada = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
      stringSerparada.add(text.substring(index, Math.min(index+2,text.length()));
      index+= 2;
}
    
22.11.2017 / 12:58
1

If you are doing it in java. You can use the "substring". I did it manually, however you can create a delimiter using a loop and repeat it over.

Ex:

    String texto = "99E65A78";
    String EX = "";

    EX = texto.substring(0, 2);
    System.out.println(EX);
    EX = texto.substring(2, 4);
    System.out.println(EX);
    EX = texto.substring(4, 6);
    System.out.println(EX);
    EX = texto.substring(6, 8);
    System.out.println(EX);
    
22.11.2017 / 12:53