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. The application in Fig. 16.6 demonstrates the use of both methods.
Figure 16.6. Substrings generated from strings.
1 // Fig. 16.6: SubString.cs 2 // Demonstrating the string Substring method. 3 using System; 4 5 class SubString 6 { 7 public static void Main() 8 { 9 string letters = "abcdefghijklmabcdefghijklm"; 10 11 // invoke Substring method and pass it one parameter 12 Console.WriteLine( "Substring from index 20 to end is "" + 13 letters.Substring( 20 ) + """ ); 14 15 // invoke Substring method and pass it two parameters 16 Console.WriteLine( "Substring from index 0 of length 6 is "" + 17 letters.Substring( 0, 6 ) + """ ); 18 } // end method Main 19 } // end class SubString
|
The statement in line 13 uses the Substring method that takes one int 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, the program throws an ArgumentOutOfRangeException.
The second version of method Substring (line 17) takes two int arguments. The first argument specifies the starting index from which the method copies characters from the original string. The second argument specifies the length of the substring to be copied. The substring returned contains a copy of the specified characters from the original string.
Concatenating strings
|