Wednesday, March 28, 2012

substring of an array. Weird results!

I've done this many times but this is a first for this problem. I have a string which I do a split on a specific char, the $ sign.

{D}United States,Lettie,C,Letas,52 Alpha Lane,4 Schilling Lane,Test City,District of Columbia,12345-
1234,betabetty@dotnet.itags.org.here.com,101-1010,121-1212,555-555-5555,Bob Beta
{B}5/30/1976,Female,5'4,110,27,118,74,127,42,85
{L}134,bettyB01,bBob1231950,What is your favorite snack?,Gum drops
$

I then want to get specific parts of the string so I do an substring on this only to get the:

Index and length must refer to a location within the string.
Parameter name: length

error message on this bit of code. b = {B} and l = {L} which can been seen in the text above.

int t1 = separateParticipants[0].IndexOf(b);
int t2 = separateParticipants[0].IndexOf(l);
litUploadError.Text = separateParticipants[0].Substring(t1,t2);

A couple things I've tested that worked correctly.

litUploadError.Text = separateParticipants[0].Substring(0,t1);

litUploadError.Text = separateParticipants[0].Substring(0,t2);

int t1 = 0;
int t2 = separateParticipants[0].IndexOf(l);
litUploadError.Text = separateParticipants[0].Substring(t1,t2);

Since they both worked with 0, it should mean that t1 and t2 exist, so why is it that when I try to get the data between t1 and t2, it gives the error?

thanks ^_^

Your problem is that you are requesting too many characters. t2 is the index of {L}, but the number of characters that come after t2 is less than the number that come after it.

To be more clear, the definition of paramters for substring is (start Index, Number Of characters); it doesn't fetch the string between two given indices.

Your last piece of code should be:

litUploadError.Text = separateParticipants[0].Substring(t1, (t2 - t1) +1);


LOL! You are so right. Can't believe I missed that. Guess I need another beer. Thanks a bunch. :)

0 comments:

Post a Comment