Tuesday, May 11, 2010

C# Truncate String

To preserve whole words when truncating, try this version: C# Truncate String - Whole Words

A simple extension method to safely truncate any string to a predetermined length:

public static string Truncate(this string str, int maxLength) {
    if (str == null) return null;
    return str.Substring(0, Math.Min(maxLength, str.Length));

Just call string.Truncate(int) and the returned string will be trimmed accordingly.


GreenDeveloping said...

Great! This helped me alot!

Alexandre ashade lassance cunha said...

Great! There is another version here, using LINQ.