用什么方法在String类只返回第N个字符? [英] What method in the String class returns only the first N characters?
本文介绍了用什么方法在String类只返回第N个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个扩展方法对字符串
类,以便如果输入字符串的长度超过规定长度 N
,只有第一个 N
字符被显示出来。
下面是它的样子:
公共静态字符串TruncateLongString(此字符串str,INT最大长度)
{
如果(str.Length< =最大长度)
返回海峡;
其他
//返回第一个最大长度的字符
}
什么字符串。*()
方法,我可以用它来只得到第一个 N
字符<$ C的$ C> STR ?
解决方案
公共静态字符串TruncateLongString(此字符串str,INT最大长度)
{
返回str.Substring(0,Math.Min(str.Length,最大长度));
}
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
?
解决方案
public static string TruncateLongString(this string str, int maxLength)
{
return str.Substring(0, Math.Min(str.Length, maxLength));
}
这篇关于用什么方法在String类只返回第N个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文