2013-07-27 37 views
0

在C#窗體窗體應用程序中,我有不同長度和格式的字符串,我希望顯示前25個字符不包含預覽中任何類型的換行符。預覽字符串應該是,後跟「...」即使當字符串小於25個字符時,從右側切割爲最多25個字符的字符串,刪除所有種類的換行符

我有一些小於25個字符的字符串,但它們也可以包含換行符或有時不能。換行符可以像<br>, <br />, /n, /r, /r/n, /n/n或像C#中的Environment.Newline。 對於較短的字符串,由於TextX.SubString(0,25)無法應用,所以我得到異常。

框架中的準備就緒的功能會做到最好的方式嗎? 也許你有任何想法如何解決這個問題。

最後應該追加「...」,但由於字符串已經定義,所以不能附加東西給它TextX.Append在內容中不存在。

回答

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 
相關問題