Mark
Mark

Reputation: 2038

What's the best way to work with a Java String that has a mapping of fields within it?

I have a long String that has a particular field layout:

Char 1-6 = the type of message
Char 7 = system number
Char 8-9 = unused
Char 10 = shift number
and so on

I understand that I can just use the String methods to work with this, but am hoping that there is something a bit better that will let me associate the fields with the positions in a more meaningful way.

Does this exist? Thanks for any help.

Upvotes: 3

Views: 158

Answers (3)

Shubham Maheshwari
Shubham Maheshwari

Reputation: 114

Have a custom class with variables each defining the type of information they represent. In the constructor for that class, pass this String and initialise the values of different fields by parsing the String. You can then seamlessly access the information the different parts of your String represents.

You can also save the original String in the object of this new class, in case the information regarding the original String is required.

Upvotes: 0

j.con
j.con

Reputation: 889

Use jsefa @FlrDataType ... for fix length record...

that way you can create a class and easily define the positions

@FlrDataType
public class MyMessage {

   @FlrField(pos = 1, length = 5)
   String messageType;

   @FlrField(pos = 6, length = 1)
   String systemNumber;

   //etc
}

here is a quick tutorial http://jsefa.sourceforge.net/quick-tutorial.html

Upvotes: 0

mailmindlin
mailmindlin

Reputation: 624

I'm not entirely sure what you want to do, but this should work:

String typeOfMessage = str.substring(0,5);
char systemNumber  =   str.charAt(6);

...and so on.

Upvotes: 1

Related Questions