Menu

Want to work with us? We're on the lookout for a talented Digital Project Manager.

We're hiring

Limit the number of words in a string using VB.Net

Web Bureau


10 November 2010 by Web Bureau

Are you limiting the number of characters you display on the page and it's cutting words off half way through?  Try this nice little function to limit the number of words in a string.

Public Shared Function fun_LimitWord(ByVal str As String, ByVal intLimit As Integer) As String

    Dim strA() As String = str.Split(" "), strNewString As String = ""
    Dim intLength As Integer = str.Length
    Dim TChrs As Int32
    Dim i As Int32, intWordCount As Integer = 1

    If strA.Length > intLimit Then

        For i = 0 To intLimit Step +1
            If intWordCount = intLimit Then
                strNewString = Left(str, TChrs)
            End If
            TChrs += strA(i).Length + 1 '(+1 for space)
            intWordCount += 1
        Next

    Else
        strNewString = str
    End If

    Return strNewString

End Function

Grow your businessStart a project with us today.