即使字符串小于25个字符,也要从右侧将其剪切为最多25个字符.删除所有类型的换行符
本文关键字:25个 字符 删除 换行符 类型 小于 字符串 | 更新日期: 2023-09-27 18:25:13
在C#窗体应用程序中,我有不同长度和格式的字符串,我希望从中显示前25个字符的预览,而不在预览中包含任何类型的换行符。预览字符串应,后跟"…"。
我有一些小于25个字符的字符串,但它们也可以包含换行符,有时也可以不包含。换行符可以像<br>, <br />, /n, /r, /r/n, /n/n
,也可以像C#中的Environment.newline。对于较短的字符串,由于TextX,我会遇到异常。无法应用SubString(0,25)。
框架中的哪些现成功能将以最佳方式实现?也许你知道如何解决这个问题。
应该在末尾附加"…",但由于字符串已经定义,因此不能在其上附加TextX。内容中不存在Append。
框架中似乎没有现成的函数,但您可以这样做:
public static String Preview(String value) {
String[] newLines = new String[] { "<br>", "<br />", "'n", "'r", Environment.NewLine };
foreach (String newLine in newLines)
value = value.Replace(newLine, ""); // <- May be space will be better here
if (text.Length > 25)
return value.Substring(0, 25) + "…";
// If you want string END, not string START, comment out the line above and uncomment this
// return value.Substring(value.Length - 25) + "…";
else
return value;
}
...
// Test sample
String text = "abcd<br>efgh'r'r'n'n1234567890zxy'n'n1234567890abc";
String result = Preview(text); // <- abcdefgh1234567890zxy1234…
String text2 = "abcd<br>efgh'r'r";
String result2 = Preview(text2); // <- abcdefgh