CSharp examples for System:String Start End
Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
/********/* w ww.j ava2 s .co m*/ * @version : 1.0.0 * @author : Ext.NET, Inc. http://www.ext.net/ * @date : 2011-06-15 * @copyright : Copyright (c) 2011, Ext.NET, Inc. (http://www.ext.net/). All rights reserved. * @license : See license.txt and http://www.ext.net/license/. ********/ using System.Web.UI; using System.Web; using System.Text.RegularExpressions; using System.Text; using System.Security.Cryptography; using System.Globalization; using System.ComponentModel; using System.Collections.Generic; using System.Collections; using System; public class Main{ /// <summary> /// Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length /// </summary> /// <param name="text">The string to truncate</param> /// <param name="length">The maximum length to allow before truncating</param> /// <param name="word">True to try to find a common work break</param> /// <returns>The converted text</returns> public static string Ellipsis(this string text, int length, bool word) { if (text != null && text.Length > length) { if (word) { string vs = text.Substring(0, length - 2); int index = Math.Max(vs.LastIndexOf(' '), Math.Max(vs.LastIndexOf('.'), Math.Max(vs.LastIndexOf('!'), vs.LastIndexOf('?')))); if (index == -1 || index < (length - 15)) { return text.Substring(0, length - 3) + "..."; } return vs.Substring(0, index) + "..."; } return text.Substring(0, length - 3) + "..."; } return text; } /// <summary> /// Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length /// </summary> /// <param name="text">The string to truncate</param> /// <param name="length">The maximum length to allow before truncating</param> /// <returns>The converted text</returns> public static string Ellipsis(this string text, int length) { return StringUtils.Ellipsis(text, length, false); } }