Index and length must refer to a location within the string.?

Subash A picture Subash A · Feb 15, 2017 · Viewed 8.7k times · Source

My input strings are

  1. inputData = "99998UNKNOWN"
  2. inputData = "01000AMEBACIDE/TRICHOM/ANTIBAC 1"
  3. inputData = "34343AMEBACIDE/TRICHOM/ANTIBACSADWA1"

ID = inputData.Substring(0,5); Name = inputData.Substring(5,30); Level = inputData.Substring(35,1);

I am getting the below error, Index and length must refer to a location within the string.

I can understand , the error is due to the length that specified in substring for "Name" is not matching with first input. Is there any way to handle this issue with any input length?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Feb 15, 2017

One approach is to add a "sentinel" suffix to the end of the string before taking substrings. Now you can add it to the data string before taking substrings from it. As long as the suffix has sufficient length, you would never get an index/length exception:

var padded = inputData.PadRight(32);
ID = padded.Substring(0, 5).Trim();
Name = padded.Substring(5, 30).Trim();
Level = padded.Substring(30, 1).Trim();

However, now your code should check if ID, Name, or Level is empty.