|
|
|
| 14 February 2002 | Word() |
| Author | W.M. Hinsch (New Mexico Mark) |
| Action | Returns the nth word from a string. |
| Syntax | Word ("string", number, ["white space characters"]) |
| Parameters | |
| Remarks | This function works hand-in-hand with the Words() UDF. For instance, if, using Words(), we placed a line from the output of an NT "ping" command into a variable, that variable might contain: $MyVar = "Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)," If we are only interested in displaying the received number we could use the Word() UDF to simply extract the portion we need: ? Word($MyVar,7)+" packets received." |
| Returns | This function returns a string containing the nth word from the source string. |
| Dependencies | None. |
| Examples |
BREAK ON
$MyWS = Chr(9) + Chr(32) + '!?.,;:'
$TS = 'This... is a complex phrase with varying spaces and punctuation!'
$TS ?
'Word 1 is: ' + Word($TS,1,$MyWS) ?
'The last word is: ' + Word($TS,-1,$MyWS) ?
'The sixth word is: ' + Word($TS,6) ? ?
$Test = "This is a test"
FOR $intCtr1 = -5 TO 5
"Word " + $intCtr1 + " is: " + Word($Test,$intCtr1) ?
NEXT
'The first word on the right side of this equation is: ' + Word('2 + 2=4',2,'=')
; Console output
;This... is a complex phrase with varying spaces and punctuation!
;Word 1 is: This
;The last word is: punctuation
;The sixth word is: with
;Word -5 is:
;Word -4 is: This
;Word -3 is: is
;Word -2 is: a
;Word -1 is: test
;Word 0 is:
;Word 1 is: This
;Word 2 is: is
;Word 3 is: a
;Word 4 is: test
;Word 5 is:
;The first word on the right side of this equation is: 4
|
| Source |
FUNCTION Word ($sstr, $iwrdnum, OPTIONAL $strws)
; Syntax: Word("string",number, ["white space characters"])
; Word number may be negative, in which case, words will be counted
; from the right of the string. I.e. -1 will return the last word in the string.
DIM $iwrdctr, $ilen, $istart, $ifinish, $istep, $i
$word=''
$sstr=''+$sstr
$strws=''+$strws
$iwrdnum=0+$iwrdnum
$ilen=Len($sstr)
$iwrdctr=0
IF ($strws = '')
$strws=Chr(9)+Chr(32)+','
ENDIF
IF ($iwrdnum >= 0) ; Parse string forward
$istart=1
$ifinish=$ilen
$istep=1
ELSE
; Parse string backward
$istart=$ilen
$ifinish=1
$istep=-1
$iwrdnum=-1*$iwrdnum
ENDIF
IF ($sstr <> '') AND ($iwrdnum > 0)
FOR $i = $istart TO $ifinish STEP $istep
IF InStr($strws,Substr($sstr,$i,1)) ; If whitespace
WHILE InStr($strws,Substr($sstr,$i,1)) AND ($i <= $ilen) ; skip it
$i=$i+$istep
LOOP
ELSE
; If non-whitespace
$iwrdctr=$iwrdctr+1 ; increment word counter
; If this is the correct word number, extract it
IF ($iwrdctr = $iwrdnum)
WHILE NOT InStr($strws,Substr($sstr,$i,1)) AND ($i <= $ilen)
; Extract it in the right order!
IF ($istep = 1)
$word=$word+Substr($sstr,$i,1)
ELSE
$word=Substr($sstr,$i,1)+$word
ENDIF
$i=$i+$istep
LOOP
ELSE
;otherwise, skip the word
WHILE NOT InStr($strws,Substr($sstr,$i,1)) AND ($i <= $ilen)
$i=$i+$istep
LOOP
ENDIF
ENDIF
$i=$i-$istep
NEXT
ENDIF
ENDFUNCTION ; - Word -
|
|
|
|