I have a 16 char string I need to parse into 4 substrings. The first substring needs to be the first 3chars, next needs to be the next 3 chars, and the last two are 5 chars each. Right now I am just using substring to break up the four. Like this:
I don't have a better solution than Andrew's. It's simple, fast and easy for a reviewer to understand.
Joined: Jan 29, 2003
The substringing solution is clear enough. If the repetition bothers you, you could hide it in a special parsing class. I worked in another language (EASEL) with "skip" and "take" syntax something like...
EASEL could also take up to a delimiter or pattern, and skip a number or a pattern. In Java this might fit best in a Stream concept. Does that look better or worse to you? [ August 03, 2006: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Jul 17, 2006
In my personal opinion, the only way to improve upon the substring version is to create a well named method out of it.
This provides 2 advantages:
1. It will make the code in the calling location clearer, because the name of the method will basically describe exactly what it does.
2. It will be re-usable.
Then, at the point where you use the method, you simply do this:
This would be the MOST clear way for the maintenance programmer to understand what that code was doing.
You could also write a variation that would use the length of each sub-string instead of the start positions, and compute the breakLocation values yourself.
- Adam [ August 03, 2006: Message edited by: Adam Nace ]