How can I separate a string for example 36529874 from two to two without having any separation carcter for example 36.52.98.74

Asked

Viewed 500 times

3

I’m taking the IMEI of the phone and I have to divide it into groups of 2 characters for me to convert them to hexa later.

This string comes without separator, the numbers come together, for example 36529874 and I wanted to separate them into groups of two numbers. So I take the String divide the first two and convert into Hexa, divide the two seconds and convert into Hexa, divide the third two and convert into Hexa. After converting these pairs into hexa I want to use only a few to show on the screen. How can I do this? I’m a beginner, I looked for a solution but I couldn’t find.

3 answers

4

Can use Regex Java thus:

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);
List<String> tokens = new LinkedList<String>();
while(m.find())
{
  String token = m.group(0);
  tokens.add(token);
}
for (String string : tokens) {
    System.out.println(string); // out 36 52 98 74
}
  • 1

    Too much waste using regex for something so simple.

  • What else could I use @Luishenrique ?

  • What would be the parameters ("[0-9]{2}"); of the line Pattern p = Pattern.compile("[0-9]{2}"); ? @Fernando

  • 1

    Substring solves your problem.

  • I saw here @Luishenrique is more practical. If you can leave an example would be cool but thank you!

  • @kaamis ,edited as new information regarding '[0-9]{2}'

  • 1

    @Luishenrique, I do not consider waste using Regex, since Regex is one of the fastest and most efficient forms of string manipulation, and it is still much more self-documenting (for those who know regular expressions) than any algorithm with substring and some for's do something similar. But please post your version with substring, so that we may have another option.

  • 1

    Too bad I saw the comment only a year later. Fast and efficient is not. It’s just practice. We exchange efficiency and speed precisely for the practicality of solving in fewer lines.

Show 3 more comments

3

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 grupos in order.

See working on Ideone

2


Since it is a String with a fixed size and the output should follow the same pattern, I suggest making it 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);
    }
}

Exit:

IMEI: 36529874; Imei_converted: 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 into the result. But as said, because it is a simple problem if using multiple String is also acceptable.

Example in Ideone

  • That exit is correct: IMEI: 36529874; IMEI_convertido: 24.34.62.4a?

  • Well, he said he wants to convert to hexa. His title leaves a bit confused because it seems he wants the output to be 36.52.98.74, but in fact he says that the entrance does not have the separation of the type 36.52.98.74. That’s what I understood from the question.

  • That’s right Math!

  • @kaamis the part you say Após converter esses pares em hexa quero usar somente alguns para mostrar na tela., depends on what characters you want to display, but you can do it using the substring() again.

  • @Math, I get it, is this question is really bad, gets the hint to the AP, try to improve this question and the future.

  • Ok, I got @Math thank you so much. Just could explain to me what this command is append and the StringBuilder? Sorry for the question @Fernando.

  • @kaamis Variables of the type String are immutable, ie at each concatenation a new variable of type String is created and the previous ones (used to concatenate) are waiting for the Garbage Collector to come clean them from memory. So when you do an operation that involves the creation of many Strings the ideal is to use the StringBuilder which is similar to class String, but is changeable, this results in a lower consumption of RAM.

  • It is possible that in my example it does not make much difference to use Strings or StringBuilder because it is a small piece of code, but by custom I used the StringBuilder. See also these questions: What is the most appropriate way to concatenate strings? (is C#, but helps to understand), How Stringbuffer() and Stringbuilder behave()? and String and its efficiency

  • Okay, thank you so much, guys. I’m sorry about my layman behavior.

Show 4 more comments

Browser other questions tagged

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