Something I find myself needing to do quite often is truncate a string to a maximum pre-determined length for display purposes. This is easily accomplished using the string.Substring(int, int) method, however this approach is limited by the fact that without checking the length of the string being truncated, the Substring() method will throw an exception if the second parameter passed to is exceeds the actual length of the string.
It's nothing fancy, but here is an extension method to truncate any string to a given length:public static string Truncate(this string str, int maxLength) {
if (str == null) return null;
return str.Substring(0, Math.Min(maxLength, str.Length));
}Simply call string.Truncate(int) and the returned string will be chopped accordingly.
0 comments:
Post a Comment