ASP.NET: Truncate a string to a set number of whole words
From Wiki
Summary: An example function to truncate a string to a set number of whole words
- Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- Label1.Text = TruncateWithWholeWords("one two three four five six seven eight nine ten " _
- & "eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen " _
- & "nineteen twenty twenty-one twenty-two twenty-three", 20)
- End Sub
- Private Function TruncateWithWholeWords(ByVal OriginalString As String, ByVal NumberOfWords As Integer) As String
- ' Declarations
- Dim strResult As New StringBuilder
- Dim strWords As String()
- ' Replace multiple spaces with single ones
- Do While (OriginalString.IndexOf(Space(2)) >= 0)
- OriginalString = OriginalString.Replace(Space(2), Space(1))
- Loop
- ' Split the string by a space
- strWords = OriginalString.Split(" ")
- ' If there aren't the required number of spaces, return the orignal string
- If strWords.GetUpperBound(0) < NumberOfWords Then
- Return OriginalString
- Else
- ' Otherwise, append each word to the new stringbuilder
- For i As Integer = 0 To NumberOfWords - 1
- strResult.Append(strWords(i) & " ")
- Next
- ' Return the required phrase
- Return strResult.ToString.Trim
- End If
- End Function
This Hack is part of the ASP.NET Hacks collection


