How to split a string every 2 characters?

Asked

Viewed 2,533 times

6

I’m trying to split a string every two characters, but I don’t have a delimiter and I need to use the whole string.

Example:

String exemplo= 99E65A78

String ex1= 99
String ex2= E6
String ex3= 5A
String ex4= 78

4 answers

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 in the repl it.. Also put on the Github for future reference.

I skip every 2 characters and keep it in a list. I just take care not to catch a character smaller than the size.

The second loop is just for show.

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

  • I would only exchange the 2 for a constant, in case it wants to vary by n characters, would have to change only in a corner. (:

  • 1

    @Felipeavelar I even thought about it and I really like the idea, I just found exaggeration to demonstrate here. I’m still going to take a look at it and I’m going to move on it too (I need to optimize time these days).

  • Thanks. Thank you very much.

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;
}
  • I think you lost the timing...

  • 1

    It’s true @Jeffersonquesado while doing it posted kkk

  • I thought it was the same answer, now that I realize you used while, so it’s slightly distinct...

1


Try it like this:

System.out.println(Arrays.toString(
    "8S8Q4D1SKCQC2C4S6H4C6DJS2S1C6C".split("(?<=\\G.{2})")
));
  • Solved. Thank you very much!!

  • 2

    Could you explain what the regex is doing.

  • 1

    You solve the problem but do not explain the solution. This does not contribute to solving the doubts of younger people in the area.

1

If you’re doing it in java. You can use "substring". I did it manually, but you can create a delimiter using a loop and work on it.

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);
  • 1

    And if the string size cannot be determined?

  • 1

    @Articuno , why the AR put as a note in the text "using loop repetition", near the observation "I did manually, however"

Browser other questions tagged

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