Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

ASP.NET: Truncate a string to a set number of whole words

From Wiki

Jump to: navigation, search

Summary: An example function to truncate a string to a set number of whole words

  1. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  2.     Label1.Text = TruncateWithWholeWords("one two three four five six seven eight nine ten " _
  3.         & "eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen " _
  4.         & "nineteen twenty twenty-one twenty-two twenty-three", 20)
  5. End Sub
  6.  
  7. Private Function TruncateWithWholeWords(ByVal OriginalString As String, ByVal NumberOfWords As Integer) As String
  8.     ' Declarations  
  9.     Dim strResult As New StringBuilder
  10.     Dim strWords As String()
  11.  
  12.     ' Replace multiple spaces with single ones  
  13.     Do While (OriginalString.IndexOf(Space(2)) >= 0)
  14.         OriginalString = OriginalString.Replace(Space(2), Space(1))
  15.     Loop
  16.  
  17.     ' Split the string by a space  
  18.     strWords = OriginalString.Split(" ")
  19.  
  20.     ' If there aren't the required number of spaces, return the orignal string  
  21.     If strWords.GetUpperBound(0) < NumberOfWords Then
  22.         Return OriginalString
  23.     Else
  24.         ' Otherwise, append each word to the new stringbuilder  
  25.         For i As Integer = 0 To NumberOfWords - 1
  26.             strResult.Append(strWords(i) & " ")
  27.         Next
  28.         ' Return the required phrase  
  29.         Return strResult.ToString.Trim
  30.     End If
  31.  
  32. End Function

This Hack is part of the ASP.NET Hacks collection

468 Rating: 1.5/5 (4 votes cast)