Truemag

  • Categories
    • Tips And Tricks
    • Internet
    • PHP
    • Javascript
    • CSharp
    • SQL Server
    • Linux
  • Lastest Videos
  • Our Demos
  • About
  • Contact
  • Home
  • Write With Us
  • Job Request
Home CSharp Simple Truncate Words Function In C#

Simple Truncate Words Function In C#

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;
    }
}

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…

Jan 11, 2012Hoan Huynh
C# Generate Random Number FunctionSHORTCUT KEYS increase your productivity
You Might Also Like:
  • Truncate And Limit Displayed Text With Selected Maximum Length PHP Function
  • PHP Show Limited Words Of A String Content Based On Max Length
  • Javascript LTrim,RTrim,Trim function
  • MSSQL Trim Function
  • CSharp Validate Internet URL Function With Regular Expression
  • MSSQL Split String Function
  • CSharp Validate Email Address Function With Regular Expression
  • Function Remove All HTML Tags In PHP
  • Check Google PageRank With PHP
  • C# Get File Extension Without Sub String Or Split Function
Hoan Huynh

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at [email protected]

10 years ago CSharpsplit, Trim292
0
GooglePlus
0
Facebook
0
Twitter
0
Digg
0
Delicious
0
Stumbleupon
0
Linkedin
0
Pinterest
Most Viewed
PHP Download Image Or File From URL
24,460 views
Notepad Plus Plus Compare Plugin
How To Install Compare Text Plugin In Notepad Plus Plus
21,839 views
Microsoft SQL Server 2008 Attach Remove Log
Delete, Shrink, Eliminate Transaction Log .LDF File
17,656 views
JQuery Allow only numeric characters or only alphabet characters in textbox
14,998 views
C# Read Json From URL And Parse/Deserialize Json
11,723 views
4 Rapid Development is a central page that is targeted at newbie and professional programmers, database administrators, system admin, web masters and bloggers.
Recent Posts
  • Things to Learn about Installingderm Loan Type S
  • Online Photo Editor – Free Photoediting Software
  • A Guide to Finding the Best Paper Sellers
  • Photoediting in Home Isn’t Hard to Do!

  • Free Photo Editor Online
Categories
  • CSharp (45)
  • Facebook Graph API (19)
  • Google API (7)
  • Internet (87)
  • iPhone XCode (8)
  • Javascript (35)
  • Linux (27)
  • MySQL (16)
  • PHP (84)
  • Problem Issue Error (29)
  • Resources (32)
  • SQL Server (25)
  • Timeline (5)
  • Tips And Tricks (141)
  • Uncategorized (647)
Recommended
  • Custom Software Development Company
  • Online Useful Tools
  • Premium Themes
  • VPS
2014 © 4 Rapid Development