What method in the String class returns only the f

2020-01-24 20:00发布

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?

11条回答
叛逆
2楼-- · 2020-01-24 20:27

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()).

查看更多
Summer. ? 凉城
3楼-- · 2020-01-24 20:29

string.Substring(0,n); // 0 - start index and n - number of characters

查看更多
做自己的国王
4楼-- · 2020-01-24 20:34
substring(int startpos, int lenght);
查看更多
Summer. ? 凉城
5楼-- · 2020-01-24 20:35
public static string TruncateLongString(this string str, int maxLength)
{
    if (string.IsNullOrEmpty(str))
        return str;
    return str.Substring(0, Math.Min(str.Length, maxLength));
}
查看更多
看我几分像从前
6楼-- · 2020-01-24 20:35
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.

查看更多
登录 后发表回答