在C#windows窗体应用程序中,我有不同长度和格式的字符串,我希望显示前25个字符的预览,而不包含预览中的任何类型的换行符。预览字符串应为,后跟“...”。
我有一些字符串少于25个字符,但它们也可以包含换行符或有时不包含换行符。换行符可以像<br>, <br />, /n, /r, /r/n, /n/n
一样,也可以像C#中的Environment.Newline一样。
由于TextX.SubString(0,25)无法应用,因此使用较短的字符串会出现异常。
框架中哪些准备好的功能最好的方式呢? 也许你知道如何解决这个问题。
最后应该附加“...”,但由于字符串已经定义,因此无法附加内容TextX.Append在内容中不存在。
答案 0 :(得分:1)
看来,框架中没有现成的功能,但你可以这样做:
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