Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

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: 0.0/5 (0 votes cast)