How convert string approximately 300 characters and then showing continuation with […] after a word break.?
我正在研究RSS提要。在rssfeed
1 2 3 4 5 6 | <description>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially [...]</description> |
代码:
1 2 3 4 5 6 | TextWriter.WriteStartElement("item"); TextWriter.WriteElementString("title", oFeedItem["CommPostSubject"].ToString()); TextWriter.WriteElementString("description", oFeedItem["CommPostDescription"]. ToString()); TextWriter.WriteElementString("link", oFeedItem["CommPostSubjectUrl"].ToString()); TextWriter.WriteEndElement(); |
如何处理字符串,方法是在换行符后显示带有[…]的继续符?
您可以为
1 2 3 4 5 6 7 8 9 10 11 12 | public static class MyExtensions{ public static string SubText(this System.String str, System.Int32 charCount, System.String continues) { if (string.IsNullOrWhiteSpace(str) || str.Length < charCount) return str; str = str.Substring(0, charCount); int i = str.LastIndexOf(""); if (i >= 0) str = str.Remove(i); str = String.Concat(str, continues); return str; } } |
并在代码中调用此扩展名:
1 2 3 | TextWriter .WriteElementString("description", oFeedItem["CommPostDescription"] .SubText(300," [...]")); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static string TextAbstract(string text, int length) { if (text == null) { return string.Empty; } if (text.Length <= length) { return text; } text = text.Substring(0, length); text = text.Substring(0, text.LastIndexOf("")); return text +"..."; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public static string Cutstring(string s, int min, int max) { string res =""; int runto = s.Length; if (s.Length > max) runto = max; for (int i = 0; i < runto; i++) { if (i > min) { if ((s[i] == ' ') || (s[i] == '_')|| (s[i] == '-')) { break; } } res += s[i]; } if (s.Length > max) res +="..."; return res; } |
通过使用采用startindex的lastindexof的重载,可以少创建一个中间字符串。
1 2 3 4 5 6 7 8 9 | if (inputString.Length > maxlen) { int breakindex = inputString.LastIndexOf("", maxlen); if (breakindex < 0) { breakindex = maxlen; } inputString = s.Substring(0, breakindex) +"..."; } |
使用
1 2 3 4 5 6 7 8 | string ShorterString =""; if ( YourLongString.Length > 300 ) { ShorterString = YourLongString.SubString ( 0, 300); ShorterString = ShorterString.SubString ( 0, ShorterString.LastIndexOf ("" ) + 1) +"..."; } else { ShorterString = YourLongString; } |
简单的解决方案:
- 取前300个字符
- 查找最后一个空格(或其他分词)
- 附加省略号
代码:
1 2 3 4 5 | var fullText ="Lorem Ipsum...."; var first300 = fullText.SubString(0, 300); var lastSpace = first300.LastIndexOf(""); var summary = string.format("{0}[...]", first300.SubString(0, lastSpace)); |