Description
- Expression is broken down into 'words' at given delimiter, and function returns the specified nth word from the stringExpression.
- If n is less than 1 or n is greater than the number of words in the Expression, then an empty string ("") is returned.
- The "string delimiter" is optional and can be any character or string.
- When delimiter is not specified, any combinations of characters with codes < 33, (including chr$(0), TAB character, CR, LF and space), used as delimiter. Obviously, space being natural choice.
- But function behaves differently then explicitly passing space character as a delimiter - see hints.
Syntax
- word$(stringExpression, n [, string delimiter])
Hints
- If you do not know, how many words you have, you just keep cycling until you get "" (empty string) - see example.
- If explicitly passing delimiter, the delimiter is returned in the case when there is nothing between the delimiters (empty field) - see example. It works for any delimiter - space, too.
- If delimiter is not set, then any combinations of characters with codes < 33 used as delimiter,
- AND:
- leading and trailing such characters are stripped from stringExpression
- several such characters count as one delimiter.
- Even though its called "word$", WORD$() will extract numbers from a string, too! All that is required is that the expression the WORD$ function is working on is a stringExpression.
- You can use more then one character as delimiter. For example, CR LF (chr$(13)+chr$(10)) will split lines in a text file, which was read into one big string.
Example
' These examples are meant to show the way to use word$.
' There are many other ways to accomplish the task they show.
' Using the default space character as a delimiter
ch$ = "One Two Three Four Five"
for i = 1 to 5
print "Chapter ";
print word$(ch$, i)
print
next i
print
' Using comma as a delimiter
ch$ = "1,2,3,4,5"
for i = 1 to 5
print "Chapter ";
print word$(ch$, i, ",")
print
next i
end
' Using the period (.) to extract sentences from a paragraph
para$ ="Word$ is a powerful function. You will find you'll use it "; _
"often in your programs. Word$ is often used to extract a particular "; _
"field from a data file, where the field delimiter is used "; _
"for the string delimiter."
for i = 1 to 3
print trim$(word$(para$, i, ".")); "."
print
next i
end
' ''You may have to use other characters as delimiters if your
' sentences end in other punctuation marks''.
'Using word$ to parse string of unknown number of words
'also note detecting of empty field (nothing between delimiters)
token$ = "*"
parseMe$ = "this,is,,a,test"
delim$=","
idx = 0
while token$<>""
idx = idx + 1
token$ = word$(parseMe$, idx, delim$)
if token$ <> "" then
if token$ = delim$ then
print token$;
print " (Actually this means we have empty field here)"
else
print token$
end if
end if
wend
Useful Procedures
' Place a useful function or sub using this keyword here