What method in the String class returns only the first N characters?
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
?
Solution 1:
public static string TruncateLongString(this string str, int maxLength)
{
if (string.IsNullOrEmpty(str)) return str;
return str.Substring(0, Math.Min(str.Length, maxLength));
}
In C# 8 or later it is also possible to use a Range to make this a bit terser:
public static string TruncateLongString(this string str, int maxLength)
{
return str?[0..Math.Min(str.Length, maxLength)];
}
Which can be further reduced using an expression body:
public static string TruncateLongString(this string str, int maxLength) =>
str?[0..Math.Min(str.Length, maxLength)];
Note null-conditional operator (?
) is there to handle the case where str
is null. This replaces the need for an explict null check.
Solution 2:
string truncatedToNLength = new string(s.Take(n).ToArray());
This solution has a tiny bonus in that if n is greater than s.Length, it still does the right thing.
Solution 3:
You can use LINQ str.Take(n)
or str.SubString(0, n)
, where the latter will throw an ArgumentOutOfRangeException
exception for n > str.Length
.
Mind that the LINQ version returns a IEnumerable<char>
, so you'd have to convert the IEnumerable<char>
to string
: new string(s.Take(n).ToArray())
.