Recipe 5.44. Splitting a String


Problem

You want to split a string using a multicharacter string rather than a single character as the split point, but the String object's Split() method only splits using one or more individual characters.

Solution

Sample code folder: Chapter 05\SplitString

You can use the Visual Basic Split() function instead of the String.Split() method, or you can pass an array of strings to String.Split().

Discussion

The following code shows the differences between using the Split() function and the String.Split() method:

 Dim quote As String = "The important thing is not to " & _    "stop questioning. --Albert Einstein" Dim strArray1() As String = Split(quote, "ing") Dim strArray2() As String = quote.Split(CChar("ing")) Dim result As New System.Text.StringBuilder Dim counter As Integer For counter = 0 To strArray1.Length - 1    result.AppendLine(strArray1(counter)) Next counter result.AppendLine(StrDup(30, "-")) For counter = 0 To strArray2.Length - 1    result.AppendLine(strArray2(counter)) Next counter MsgBox(result.ToString()) 

String array strArray1 is created by applying the Split() function to the sample string, splitting the string at all occurrences of "ing". strArray2 uses the String.Split() method to do the same thing. However, even though the string "ing" is passed to the String.Split() method to define the split points, only the first character of this string, the character "i," is used to make the splits. The results of these two splits are quite different, as shown in the output displayed in the message box in Figure 5-52.

Figure 5-52. Results of passing the Split( ) function and the Split( ) method a multicharacter string as the split point


To confuse the issue even further, it is possible to use the String.Split() method to split a string at whole substring boundaries, but only by passing an array of strings to the method to define the split points (not just a simple string) and passing a required parameter defining split options. The following two lines of code demonstrate this technique, returning the desired results. The first line uses the Visual Basic function, and the second line uses the string array technique just described:

 Dim strArray1() As String = Split(quote, "ing") Dim strArray1() As String = _    quote.Split(New String() {"ing"}, StringSplitOptions.None) 

Both String() options are very powerful and useful, but you do need to use the correct one, passing appropriate parameters.

See Also

Recipe 5.28 also discusses string parsing using Split().




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net