1

I have a string of length 2000. It has a fixed format. I need to split it with various lengths. Right now I am using String.substring() method for the same. I need to split it for 70 times. Is there any better way to do this.

//code

 String rawString = "01304456789AGASTECH.....";
 String fisrtStr = rawString.substring(0,2);
 String secondStr = rawString.substring(2,8);
 String otherStr = rawString.substring(8,10); and so on
  • How many lengths do you have to split it? – Abdelhak Mar 31 '16 at 12:22
  • What are you trying to do with it afterwards? 1. you could loop using the substring. 2. you could use a regular expression to split it. You might find this helpful: http://stackoverflow.com/questions/9276639/java-how-to-split-a-string-by-a-number-of-characters – philoniare Mar 31 '16 at 12:22
  • Define "better", please. – CPerkins Mar 31 '16 at 12:25
  • I need to split it 70 times – Ramachandra Reddy Mar 31 '16 at 12:27
  • I think "better" is relatively self explanatory in this context. You want to be able to extract the fields without `.substring(102,122)` sort of code, which is prone to manual error and not very maintainable - given the number of fields. – vikingsteve Mar 31 '16 at 13:44

3 Answers3

2

You could look at the smooks framework, which can convert from comma-separated or fixed length fields "CSV" formats.

Here's a relevant section in the User Guide.

Small amount of boilerplate code, but it's relatively easy to define a list of fields (each one having a character length) and a pojo which they map to.

Edit: I found some smooks-examples on github.

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
1

You can save the split indices in a list or array and iterate over it with a loop.

An other option is that you put a unique split ode into your string, so you can use the split(uniqueCode) method, if possible.

Dimitrios Begnis
  • 823
  • 6
  • 16
0

Well, you can write a helper method easily:

static List<String> splitFixed(String s, int... sizes) {
    List<String> res = new ArrayList<>(sizes.length);
    int pos = 0;
    for (int size : sizes) {
        res.add(s.substring(pos, pos + size));
        pos += size;
    }
    return res;
}

Then, if you have a few sizes, call:

List<String> items = splitFixed("01ABC02", 2, 3, 2);   // returns [01, ABC, 02]

If you have long list of sizes, first define a static final array describing your format:

final static int[] SIZES = { 2, 6, 2, ... };

//...

List<String> items = splitFixed(input, SIZES);
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67