# How can I separate a string eg 36529874 two by two without having any separation character eg 36.52.98.74

Posted on

#### Question :

I’m getting the IMEI from the phone and I have to split it into groups of 2 characters so I convert them to hex afterwards.

This String comes with no separator, the numbers come together, for example 36529874 and I wanted to separate them into groups of two numbers. So I get the String I split the first two and convert to hex, split the two seconds and convert to hex, split the two thirds and convert to hex. After converting these pairs into hexes I want to use only a few to display on the screen. How can I do this? I’m a beginner, I looked for a solution but I did not find it.

As this is a String with a fixed size and the output should follow the same pattern, I suggest doing as simple as possible:

``````public class ConverteIMEI {
public static void main(String[] args) {
String IMEI = "36529874";
StringBuilder IMEI_convertido = new StringBuilder();
IMEI_convertido.append(
Integer.toHexString(Integer.parseInt(IMEI.substring(0, 2)))).
append(".").append(
Integer.toHexString(Integer.parseInt(IMEI.substring(2, 4)))).
append(".").append(
Integer.toHexString(Integer.parseInt(IMEI.substring(4, 6)))).
append(".").append(
Integer.toHexString(Integer.parseInt(IMEI.substring(6, 8))));
System.out.println("IMEI: " + IMEI + "; IMEI_convertido: " + IMEI_convertido);
}
}
``````

Output:

IMEI: 36529874; IMEI_convertido: 24.34.62.4a

I used StringBuilder because they are several operations of `append()` so if you used String you would create a lot of String objects to concatenate in the result. But as I said, because it is a simple problem if using multiple String is also acceptable.

You can use Regex Java like this:

``````String test = "36529874";

// regex para números de 2 em 2
// [0-9] = todos os números de 0 a 9
// {2} = agrupar de 2 em 2
// Você poderia também utilizar simplesmente isso: {2}, ele irá pegar de 2 em 2 sem considerar se é numero ou não
Pattern p = Pattern.compile("[0-9]{2}");
Matcher m = p.matcher(test);
while(m.find())
{
String token = m.group(0);
}
for (String string : tokens) {
System.out.println(string); // out 36 52 98 74
}
``````

You can separate using substring.

``````String imei = "36529874";
int size = imei.length()/2;
String[] grupos = new String[size];
for (int i = 0; i < size; i++) {
grupos[i] = imei.substring(i*2, i*2+2);
}
``````

You will have the answer in the% vector of% in order.

See working at Ideone