简体   繁体   English

如何在有限字符(包括空格)内截断字符串

[英]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.

相关问题 网格视图列中的大小受限制(截断字符串长度) - Limited size in grid view column(truncate string length) 通过有限的C#拆分空间来拆分字符串 - Split String by space with limited splitting C# 在程序文件中包含SQL用户(具有有限权限)的安全隐患 - Security Implications of Including SQL User (with limited permissions) Within the Program File String Unlimited仍然限制为4000个字符? - String Unlimited still limited to 4000 characters? 如何将包含特殊字符的C#字符串传递给MySQL - How to pass a C# string to MySQL including special characters 在保存到数据库表之前,如何截断从UI控件获取的多余字符串字符? - How to truncate extra string characters get from UI control before saving to database table? 如何截断字符串以适应容器? - How to truncate a string to fit in a container? 如何嵌入空间有限的数字签名 - How to embed a digital signature with limited space 如何在字符串C#中的最后3个字符前插入空格? - How to insert space before the last 3 characters in a string C#? 如何在包含转义字符的字符串中合并或注入“@”字符,而无需在C#中从头开始定义字符串varibale - how to merge or inject “@” character in a string including escape characters without definning the string varibale from scratch in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM