[英]How to Truncate String within Limited Characters including space
I'm trying to limit the number of characters in a string. 我正在尝试限制字符串中的字符数。
However when I try the following: 但是,当我尝试以下内容时:
Truncate.TruncateString(_longString, 300);
I Still get spaces included beyond 300 characters. 我仍然获得超过300个字符的空格。 Is there an alternative so that spaces are counted within the character limit?
是否有替代方案,以便在字符限制内计算空格?
public static string TruncateString (this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.SubString(0, maxChars) + "...";
}
If you don't need the trailing spaces (and often you don't), you can always do this: 如果您不需要尾随空格(通常不需要),您可以随时执行此操作:
Truncate.TruncateString(_longstring, 300).Trim();
Edit 编辑
Although this answer was accepted as correct, the right way is actually to leave the Trim()
out of the above statement and instead to put it here: 虽然这个答案被认为是正确的,但正确的方法实际上是将
Trim()
从上面的语句中删除而不是把它放在这里:
public static string TruncateString (this string value, int maxChars)
{
value = value.trim();
return value.Length <= maxChars ? value : value.SubString(0, maxChars).Trim() + "...";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.