Marwan Alayli
Marwan Alayli

Reputation: 65

how to split a string going backwards in java

I have a binary string which i would like to split. The string is of variable length and needs to be split into 3 sections; The tag, index, and block offset. I have the length of the index and the block offset, but not the tag, and I am trying to separate the tag from the rest of the string. is there a way to do that when the length of the index and block offset are known? (I want to split them backwards because the tag is of variable length but the index and block offset are constant)


Example(written in hex for simplicity):

String[1]: 400341a0
String[2]: df7c48
index length: 2 hex
block offset length: 3 hex    
Output[0]: {400, 34, 1a0}
Output[1]: {d, f7, c48}

Upvotes: 0

Views: 484

Answers (1)

BobTheBuilder
BobTheBuilder

Reputation: 19284

Not sure about +-1 but I think it's good.

int length = s.length;
int blockOffsetIndex = length - BLOCK_OFFSET_LENGTH;
blockOffset = s.substring(blockOffsetIndex  - 1, length );

int indexIndex = blockOffsetIndex - INDEX_LENGTH;
indexStr = s.substring(indexIndex - 1, indexIndex + INDEX_LENGHT);

rest = s.substring(0, indexIndex -1);

As @sdk suggested, Apache StringUtils is also a very good solution.

Upvotes: 2

Related Questions