# 81. Last Word

# Description

Extracts the last word from a text string or variable.

# Code

Loop Version:

// set up the loop

SET Temp-n TO LENGTH( TextVar )

SET LoopLimit-n[ Temp-n ] TO 1

SET Pos-n TO Temp-n

SET Found-b TO FALSE

// loop backwards through the string

// to locate the last space

REPEAT Loop

IF Found-b = FALSE

IF MID( TextVar, Pos-n, 1 ) = " "

SET Found-b TO TRUE

ELSE

SET Pos-n TO Pos-n - 1

END IF

END IF

END REPEAT

SET LoopLimit-n[ Temp-n ] TO UNANSWERED

// extract everything after the last space

LAST( TextVar, LENGTH( TextVar ) - Pos-n )

Safe Version:

"«TextVar»"

SET Temp-n TO POSITION( RESULT, " " )

IF Temp-n > 0

LAST( RESULT, LENGTH( RESULT ) - Temp-n )

SET Temp-n TO POSITION( RESULT, " " )

IF Temp-n > 0

LAST( RESULT, LENGTH( RESULT ) - Temp-n )

SET Temp-n TO POSITION( RESULT, " " )

IF Temp-n > 0

LAST( RESULT, LENGTH( RESULT ) - Temp-n )

SET Temp-n TO POSITION( RESULT, " " )

IF Temp-n > 0

LAST( RESULT, LENGTH( RESULT ) - Temp-n )

END IF

END IF

END IF

END IF

# Explanation

The "Loop Version" of the computation will handle a string of any size. It works by stepping backwards through the string one character at a time until it finds a space. This is the space before the last word. The position of this space is kept in the temporary number variable Pos-n. Finally, everything in the string after Pos-n is returned by the computation, which will be the last word of the string.

The computation requires three temporary variables: Temp-n which holds the length of the string, Pos-n which holds the position of the last character checked as well as the position of the final space in the string, and Found-b, a TRUE/FALSE variable which tells us whether the final space has been found yet. The computation also uses the looping mechanism described in Computation 15: Loops Via REPEAT.

CAVEAT: It has been reported that this looping mechanism no longer functions in HotDocs Online. This should be a warning flag that it may not be supported in future versions of HotDocs. It still works as of HotDocs 5.3. If this is of concern to you, use the "Safe Version" of the computation described below.

The "Safe Version" should be forward-compatible with future versions of HotDocs, but is limited to a five-word string. The computation looks for the first available space in the string and cuts off everything before it. It repeats this process four times, which is why it is only good up to five words. Beyond that, you'll have to add more levels. The computation requires one temporary number variable, Temp-n, to store the position of spaces in the string.