A Safe String.SubString Extension Method
The String.Substring method in .net is useful, but has one slight quirk: If you try to read too much (i.e. "123".Substring(1,5)), you get an ArgumentOutOfRangeException saying that "Index and length must refer to a location within the string.". Here is an extension method that will not throw an exception, but instead return a truncated string, even it it is shorter than desired. That way, you can use it as a way to always Truncate longer strings while leaving shorter ones unchanged.
public static class StringExtensions { public static string SafeSubstring(this string input, int startIndex, int length) { // Todo: Check that startIndex + length does not cause an arithmetic overflow if (input.Length >= (startIndex + length)) { return input.Substring(startIndex, length); } else { if (input.Length > startIndex) { return input.Substring(startIndex); } else { return string.Empty; } } } }
This was inspired by a Question on StackOverflow, and since I needed this so many times now, I've decided to write it.
Note that this requires the .net 3.5 Compiler.
Cool,
split can be used in this example as well
Thanks
A small correction : the .NET 3.5 compiler
Indeed. It's the C# 3.0 Compiler included in .net 3.5. Confusing Version numbers 🙂
Got bitten by these confusing numbers myself too. Ah well, these confusions will end in 4.0 🙂
Good simple technique to solve this common problem. I did the same but a slight modification to reduce the lines of code and make it a little cleaner.
public static string SafeSubstring(this string source, int startIndex, int length)
{
if (startIndex > source.Length-1)
{
throw new ArgumentException("Start index cannot be greater than string length.", "startIndex");
}
return startIndex + length > source.Length ? source.Substring(startIndex) : source.Substring(startIndex, length);
}