Note that there are some explanatory texts on larger screens.

plurals
  1. POgetting string.substring(N) not to choke when N > string.length
    text
    copied!<p>I'm writing some code that takes a report from the mainframe and converts it to a spreadsheet.</p> <p>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.</p> <p>It's working okay now, but I need to get it more stable before I release it for testing.</p> <p>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</p> <pre><code>dim s as string = someStream.readline a = s.substring(10, 5) b = s.substring(16, 5) c = s.substring(22, 5) </code></pre> <p>because it'll choke when it substrings past the length of the string.</p> <p>I know I could test the length of the string before processing each row, and I <em>have</em> 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.</p> <p>If it matters, <a href="http://vbnet.pastebin.com/Yei5CiT3" rel="nofollow noreferrer">here's my code so far</a> (it's really crufty at the moment). You can see some of my/its idiocy in the processSection#data subs</p> <p>So, I'm wondering </p> <p>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? </p> <p>and</p> <p>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?</p> <p><strong>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. :)</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload