getting string.substring(N) not to choke when N > string.length
- by aape
I'm writing some code that takes a report from the mainframe and converts it to a spreadsheet.
They can't edit the code on the MF to give me a delimited file, so I'm stuck dealing with it as fixed width.
It's working okay now, but I need to get it more stable before I release it for testing.
My problem is that in any given line of data, say it could have three columns of numbers, each five chars wide at positions 10, 16, and 22. If on this one particular row, there's no data for the last two cols, it won't be padded with spaces; rather, the length of the string will be only 14. So, I can't just blindly have
dim s as string = someStream.readline
a = s.substring(10, 5)
b = s.substring(16, 5)
c = s.substring(22, 5)
because it'll choke when it substrings past the length of the string.
I know I could test the length of the string before processing each row, and I have automated the filling of some of the vsariables using a counter and a loop, and using the counter*theWidthOfTheGivenVariable to jump around, but this project was a dog to start with (come on! turning a report into a spreadsheet?), but there are many different types of rows (it's not just a grid), and the code's getting ugly fast. I'd like this to be clean, clear, and maintainable for the poor sucker that gets this after me.
If it matters, here's my code so far (it's really crufty at the moment). You can see some of my/its idiocy in the processSection#data subs
So, I'm wondering
1) is there a way baked in to .NET to have string.substring not error when reading past the end of a string without wrapping it in a try...catch?
and
2) would it be appropriate in this situation to write a new string class that inherits from string that has a more friendly substring function in it?
ETA: Thanks for all the advice and knowledge everyone. I'll go with the extension.
Hopefully one of these years, I'll get my chops up enough to pay someone back in kind. :)