tags:

views:

198

answers:

3

Hi is there away to detect the length of a byte before I get the error message:

Length cannot be less than zero. Parameter name: length

I get the error on this line:

new_username = new_username.Substring(0, new_username.IndexOf(" Joined "))

I am removing the "joined" from the string I get....how can I ignore it is "joined" isnt the the data?

Thanks

+1  A: 

Try this:

new_username = new_Username.Replace(" Joined ", "")

Be warned that this will remove all occurrences of the " Joined " substring rather than just the first.

Joel Coehoorn
If the initial string has only a username and the optional string " joined", with nothing else, this will work great!
Michael Haren
Also provided no one has " joined" as part of their username :/
Michael Haren
@Michael: .IndexOf()-based code would fail in that case as well.
Joel Coehoorn
A: 

It looks like new_username.IndexOf(" Joined ") is returning -1 meaning the string " Joined" was not found by Substring. I would break this out into two statements:

The error you are seeing is that you are effectively making this call:

new_username = new_username.Substring(0, -1)
Andrew Hare
+2  A: 

I would test to see what IndexOf returned before using it in this context:

if(new_username.IndexOf(" Joined") > 0)
{
      new_username = new_username.Substring(0, new_username.IndexOf(" Joined "))
}
Andy Rose
Thanks! That works great =)
That's inefficient since you're calling IndexOf twice. Best to call once and cache it for use in both places.
ctacke
It's probably worth checking the MSIL before doing that optimization - I think the compiler can optimise the second call away where there are no side-effects.
Richard Gadsden
@ctake forgive my ignorance, but how would you do that ? Create a new variable ?
spacemonkeys