Section 16.7. Extracting Substrings from Strings


16.7. Extracting Substrings from Strings

Class String provides two Substring methods, which are used to create a new String by copying part of an existing String. Each method returns a new String. Figure 16.6 demonstrates both methods.

Figure 16.6. Substrings generated from Strings.

  1  ' Fig. 16.6: SubString.vb  2  ' Demonstrating the String Substring method.  3  4  Module SubString  5     Sub Main()  6        Dim letters As String = "abcdefghijklmabcdefghijklm"  7        Dim output As String = ""  8  9        ' invoke Substring method and pass it one parameter 10        Console.WriteLine("Substring from index 20 to end is """ & _ 11           letters.Substring(20) & """") 12 13        ' invoke Substring method and pass it two parameters 14        Console.WriteLine("Substring from index 0 of length 6 is """ & _ 15           letters.Substring(0, 6) & """") 16     End Sub ' Main 17  End Module ' SubString 

 Substring from index 20 to end is "hijklm" Substring from index 0 of length 6 is "abcdef" 



Line 11 uses the Substring method that takes one Integer argument. The argument specifies the starting index from which the method copies characters in the original String. The substring returned contains a copy of the characters from the starting index to the end of the String. If the index specified in the argument is outside the bounds of the String, an ArgumentOutOfRangeException occurs.

The second version of method Substring (line 15) takes two Integer arguments. The arguments specify the starting index from which to copy characters and the length of the substring to copy. The substring returned contains a copy of the specified characters from the original String. If the starting index plus the length is greater than the number of characters in the String, an ArgumentOutOfRangeException occurs.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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