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?
In C# 8 or later it is also possible to use a Range to make this a bit terser:
Which can be further reduced using an expression body:
Note null-conditional operator (
?) is there to handle the case wherestris null. This replaces the need for an explict null check.