| P | 07 3278 4325 |
| M | 0420 837 445 |
| E | support@ andrewrowlings.com |
| Post | PO Box 2004 Graceville East QLD 4075 |
| ABN | 202 3456 3434 |
Focused on software development with a professional approach and a commitment to quality.
31st May 2006
Imagine that an application receives text messages that contain name-value pairs. It has to perform the following tasks:
What I provide here is a strategy implemented in VB.NET.
SplitIt is assumed that each message will contain no duplicate names. This means that the "name" part of each "name-value" pair is in effect a "key". An example string for parsing could be
Y=36|Z1=100|2W=36|F=4070|24B=S|A2=DRW23S|LL=10000|GHT=Y|PI=299
The first step is to isolate the name-value pairs. This can be done with the Split function which is a member of the String class
Dim strMessage As String Dim astrRawNameValuePairs() As String strMessage = "Y=36|Z1=100|2W=36|F=4070|24B=S|" & _ A2=DRW23S|LL=10000|GHT=Y|PI=299" astrRawNameValuePairs = strMessage.Split(New Char() {"|"})
Note that there is another Split function available which is the old VB 6 one. It is contained in the Microsoft.VisualBasic.String namespace. Microsoft.VisualBasic gets automatically imported by Visual Studio for any VB.NET project types.
StringDictionaryastrRawNameValuePairs now contains all the name-value pairs. But this is an array so the options for finding a specific "key" are limited. And each element in the array still needs to be parsed out to separate the "key" and the "value". The tasks that are of most interest are:
The following code helps achieve these tasks:
Dim strNameValueInstance As String Dim pair() As String Dim sdAccessibleNameValuePairs As _ New System.Collections.Specialized.StringDictionary For Each strNameValueInstance In astrRawNameValuePairs pair = strNameValueInstance.Split(New Char() {"="}) sdAccessibleNameValuePairs.Add(pair(0), pair(1)) Next
The StringDictionary is ideal here. It is a strongly-typed version of the Hashtable class - both keys and values must be strings. Using the StringDictionary instead of the Hashtable offers a performance advantage as there is no need for boxing, and a maintainability advantage as there isn't the risk of run-time errors caused by unexpected objects getting into the collection.
So, the questions remain:
If sdAccessibleNameValuePairs.ContainsKey("Z") Then ... End If
Dim strItemZ As String = sdAccessibleNameValuePairs.Item("Z") ' or simply ... strItemZ = sdAccessibleNameValuePairs("Z")
The stated objectives have been met. The message has been parsed and the information has been extracted into a StringDictionary which provides quick and precise access to the data.