What method in the String class returns only the first N characters?

Richard77 picture Richard77 · Aug 25, 2010 · Viewed 194.6k times · Source

I'd like to write an extension method to the String class so that if the input string to is longer than the provided length N, only the first N characters are to be displayed.

Here's how it looks like:

public static string TruncateLongString(this string str, int maxLength)
{
    if (str.Length <= maxLength)
        return str;
    else
        //return the first maxLength characters                
}

What String.*() method can I use to get only the first N characters of str?

Answer

Paul Ruane picture Paul Ruane · Aug 25, 2010
public static string TruncateLongString(this string str, int maxLength)
{
    if (string.IsNullOrEmpty(str))
        return str;
    return str.Substring(0, Math.Min(str.Length, maxLength));
}