Example 1 (lastWord) Overview

Top  Previous  Next

Here's a function that returns the last word of the phrase in the parameter sourceStr. At the very least, this code doesn't scan very well - it's hard to see what's going on.

 

lastWord1

 

 

If you want to cut-and-paste to try this example, here's the text of the function for you to paste into any VB module:

Function lastWord(sourceStr As String, _

                  Optional delimiters As String = _

                  " .,;'[]\=-_+{}|"":?><") As String

Dim nextChar As String

Dim i As Integer

i = Len(sourceStr)

 

'if we're passed an empty string, return an empty string

If i = 0 Then

    lastWord = sourceStr

    Exit Function

End If

 

Do While (i > 0) And (InStr(delimiters, Mid$(sourceStr, i, 1)) > 0)

    i = i - 1

Loop

 

If i = 0 Then 'there are no delimiters in the source string

    lastWord = sourceStr

    Exit Function

End If

 

Dim ans As String

 

Do While (InStr(delimiters, Mid$(sourceStr, i, 1)) = 0) And (i > 0)

    ans = Mid$(sourceStr, i, 1) & ans

    i = i - 1

    If i = 0 Then Exit Do

Loop

 

lastWord = ans

End Function