Below is just a simple C# function that truncates or cut off a long text with a defined maximum word count number. A shorter text might be returned with dot dot dot (…) if its original length is not higher than the specified number. Otherwise, the full text will be returned.
The truncate words function is useful when you would like to display a short content (excerpt) or piece of original content instead of displaying full content especially in home page or a page that displays a list of entries. This makes your design clean, not too long and keep user experience.
The function is written in Csharp (C#) and demonstration is in a ASP.NET page. And you’re free to replace dot dot dot (…) characters with a Read more link or something you want to open the full content.
C# Truncate Words Function
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class truncate_words : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string text = "Do your layouts deserve better than Lorem Ipsum? Apply as an art director and team up with the best copywriters at Jung von Matt: www.jvm.com/jobs/lipsum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus neque erat, malesuada non ornare eget, faucibus eget sem. Proin porttitor gravida nisi et vehicula. Vestibulum sollicitudin mi eget nunc sollicitudin sollicitudin. Nunc nulla mauris, hendrerit non semper vel, cursus nec sapien. Praesent consequat arcu id metus rutrum quis posuere quam venenatis. Vivamus eros magna, luctus sed auctor sit amet, aliquam eget tellus. Vivamus vitae sem odio. Donec eu augue et velit vulputate dictum in in orci. Donec ornare sem mi. Nunc ligula risus, blandit vitae convallis ut, condimentum pulvinar purus."; int wordCount = 10; Response.Write(TruncateWords(text, wordCount)); } private string TruncateWords(string text, int wordCount) { string output = String.Empty; if (text.Length > 0) { string[] words = text.Split(' '); if (words.Length < wordCount) wordCount = words.Length; for (int x = 0; x <= wordCount; x++) output += words[x] + " "; if (words.Length > wordCount) output = output.Trim() + "..."; } return output; } } |
Output: Do your layouts deserve better than Lorem Ipsum? Apply as an…