0

I'm new to Java and didn't find any exact solution for my scenario. I have a large string which is 1500 length.

For example : String inData = "THISKALJSKAJFDSKJDKSJ KSJDLKJSFKD LSKJDFKSJ, ASA:..";

I have a fixed format for these 1500 length. I have to split the string into 200+ fields based on each field fixed length. I found something like below.

String firstFld = inData.substring(0, 2);

String secondFld = inData.substring(3, 10);

String thirdFld = inData.substring(11, 13);

can anyone please suggest with better way of doing the split instead of declaring 200 string variables and store them there or loading them to a String Array ? I plan to to build an xml with all these fields after getting them.

I appreciate all your help!

6
  • 1
    use an array of length 200 Commented Mar 21, 2017 at 20:25
  • 1
    You could split the string into an Array or List Commented Mar 21, 2017 at 20:25
  • 1
    What is the fixed format? Is it stored anywhere in your code? Commented Mar 21, 2017 at 20:26
  • 1
    Maybe try to learn the basics (arrays, collections etc.) before you start working with XML. Commented Mar 21, 2017 at 20:28
  • 1
    the fixed length is stored in a file. I understand I could add this to an array. But if there any other better options ? I updated the question to include the string array as an option. Commented Mar 21, 2017 at 20:34

1 Answer 1

1

Well, if it's two of the below, then this would work:

  1. There's a pattern for the field lengths: like (0,2), (3, 10), (11,13), (14, 21) ...
  2. You have a list of field lengths

In both cases it is pretty simple to solve what you want:

First Case: Pattern is 2 chars -> 7 chars starting with 2

String[] fields = new String[getNumberOfFields(1500)];
int curr = 0;
for(int i = 0 ; i < fields.length; i++) {
    if(i % 2 == 0) {
        fields[i] = inData.substring(curr, curr+7);
        curr+=8;
    } else {
        fields[i] = inData.substring(curr, curr+2);
        curr+=3;
    }
}

Second Case: You have a bunch of different field lenghts

int curr = 0;
String[] fields = new String[fieldLengths.length];
for(int i = 0; i < fieldLengths.length; i++) {
     fields[i] = inData.substring(curr, curr+fieldLengths[i]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

If the pattern is more complex though, I would implement it a different way, dependent on how complex and on what it was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.