Counting Fields in a Delimited String (or Words in a String)

Category:
String Manipulation
Type:
Snippets
Difficulty:
Beginning
Author:
Gavin Bollard

Version Compatibility: Visual Basic 6, Visual Basic 5

More information:
This routine was written when I was handling a series of comma delimited files (of varying sizes). I used the vb line input statement to read a line from the file into memory, and needed to be able to determine how many fields (separate data items were in it).

For example - the following string contains four fields (this routine would return a 4).

Roger Wilco, 02 9805 9809, Space Fleet Headquarters, Janitor

Since sentances are delimited by spaces, this routine could also be used to count the number of words in a string (by passing a single space as a delimiter).

This is especially useful for VB5, because in VB6 you can do a similiar thing with fewer lines of code using the Split function.

Instructions: Copy the declarations and code below and paste directly into your VB project.

Declarations:

Code: