This section covers a more-practical class that exposes three methods for manipulating strings. I have used these methods in many projects, and I’m sure many readers will have good use for them — at least one of them. The first two methods are the ExtractPathName and ExtractFile-Name methods, which extract the filename and pathname from a full filename. If the full name of a file is C:\Documents\Recipes\Chinese\Won Ton.txt, the ExtractPathName method will return the substring C:\Documents\Recipes\Chinese\, and the ExtractFileName method will return the substring Won Ton.txt.
You can use the Split method of the String class to extract all the parts of a delimited string. Extracting the pathname and filename of a complete filename is so common in programming that it’s a good idea to implement the corresponding functions as methods in a custom class. You can also use the Path object, which exposes a similar functionality. (The Path object is discussed in Chapter, “Accessing Folders and Files.”)
The third method,which is called Num2String, converts numeric values (amounts) to the equivalent strings. For example, it can convert the amount $12,544 to the string Twelve Thousand, Five Hundred And Forty Four dollars. No other class in the Framework provides this functionality, and any program that prints checks can use this class.
Parsing a Filename
Let’s start with the two methods that parse a complete filename. These methods are implemented as Public functions, and they’re quite simple. Start a new project, rename the form to TestForm, and add a Class to the project. Name the class and the project StringTools. Then enter the code of Listing 6.22 in the Class module.
Listing 6.22: The ExtractFileName and ExtractPathName Methods
Code language: VB.NET (vbnet)
Public Function ExtractFileName(ByVal PathFileName As String) As String Dim delimiterPosition As Integer delimiterPosition = PathFileName.LastIndexOf("\") If delimiterPosition > 0 Then Return PathFileName.Substring(delimiterPosition + 1) Else Return PathFileName End If End Function Public Function ExtractPathName(ByVal PathFileName As String) As String Dim delimiterPosition As Integer delimiterPosition = PathFileName.LastIndexOf("\") If delimiterPosition > 0 Then Return PathFileName.Substring(0, delimiterPosition) Else Return "" End If End Function
These are two simple functions that parse the string passed as an argument. If the string contains no delimiter, it’s assumed that the entire argument is just a filename.