Left
public static string Left(this string value, int length) { if (string.IsNullOrEmpty(value)) { return value; } return value.Substring(0, length); }
Mid
public static string Mid(this string value, int startPosition, int endPosition) { if (string.IsNullOrEmpty(value)) { return value; } return value.Substring(startPosition, endPosition); }
Right
public static string Right(this string value, int length) { if (string.IsNullOrEmpty(value)) { return value; } return value.Substring(value.Length - length); }
Then you could use them like this:
someString.Left(5); someString.Mid(5, 20); someString.Right(9);
Note that I'm not really sanitizing any exceptions that may occur, like, for example, if the string passed in is smaller than the one we try to get. You should implement that defensive code yourself. :)
These work, but if you really want "Mid" to function like Visual Basic then this needs an update (though I think your implementation is better in a .Net sense). Anyway, VB's Mid is based on a index starting at 1 instead of .Net's standard 0 (for compaitiblity dating back to the old school basic days).
ReplyDeleteIn the mid function, the following would make it behave like VB by changing the start index:
return value.Substring(startPosition - 1, endPosition);
Thank you for your feedback.
DeleteThe code that I posted reproduces the VB functions in C#, so it wouldn't really make sense to keep it as a 1-based index like VB was. But thank you anyway.
Awesome. That was perfect. Thanks.
ReplyDelete