Want to work with us? We're on the lookout for digital experts.

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

        strNewString = str
    End If

    Return strNewString

End Function

Grow your businessStart a project with us today.

This site uses essential cookies for parts of the site to operate and have already been set. Find out more about how we use cookies and how you may delete them. You may delete cookies, but parts of the site will not work.