参见英文答案 >
How do I truncate a .NET string?25个
我试过以下:
我试过以下:
var Title = LongTitle.Substring(0,20)
如果LongTitle的长度小于20,那么它可以工作,但是如果将字符串限制在最多20个字符,但是如果它们仅仅是例如5个字符长则不能得到错误.
解决方法
确保长度不会超过LongTitle(跳过空检查):
int maxLength = Math.Min(LongTitle.Length,20); string title = LongTitle.Substring(0,maxLength);
这可以变成扩展方法:
public static class StringExtensions { /// <summary> /// Truncates string so that it is no longer than the specified number of characters. /// </summary> /// <param name="str">String to truncate.</param> /// <param name="length">Maximum string length.</param> /// <returns>Original string or a truncated one if the original was too long.</returns> public static string Truncate(this string str,int length) { if(length < 0) { throw new ArgumentOutOfRangeException("length","Length must be >= 0"); } if (str == null) { return null; } int maxLength = Math.Min(str.Length,length); return str.Substring(0,maxLength); } }
哪个可以用作:
string title = LongTitle.Truncate(20);