简体   繁体   中英

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM