0

在 C# windows 窗体应用程序中,我有不同长度和格式的字符串,我想从中显示前 25 个字符的预览,而不在预览中包含任何类型的换行符。预览字符串后应跟“...”

我有一些少于 25 个字符的字符串,但它们也可以包含换行符,有时也可以不包含。换行符可以类似于<br>, <br />, /n, /r, /r/n, /n/nC# 中的 Environment.Newline。对于较短的字符串,由于无法应用 TextX.SubString(0, 25) ,我会遇到异常。

框架中的哪些准备好的功能会以最好的方式做到这一点?也许你知道如何解决这个问题。

最后应附加“...”,但由于字符串已定义,因此无法附加任何内容。 TextX.Append 在内容中不存在。

4

1 回答 1

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
于 2013-07-27T12:37:21.703 回答