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.

3 comments:

GreenDeveloping said...
This comment has been removed by the author.
GreenDeveloping said...

Great! This helped me alot!

Alexandre ashade lassance cunha said...

Great! There is another version here, using LINQ.