16.4. String Indexer, Length Property and CopyTo MethodFigure 16.2 uses the String indexer to access individual characters in a String, and demonstrates String property Length, which returns the length of the String. The program also uses String method CopyTo to copy a specified number of characters from a String into a Char array. This application determines the length of a String, reverses the order of the characters in the String and copies a series of characters from the String to a character array. Figure 16.2. String indexer, Length property and CopyTo method.
Line 17 uses String property Length to determine the number of characters in string1. Like arrays, Strings always know their own size. Lines 2426 output the characters of string1 in reverse order using the String indexer, which treats a String as an array of Chars and returns the character at a specific index in the String. The indexer receives an integer argument as the index and returns the character at that index. As with arrays, the first element of a String is considered to be at position 0. Common Programming Error 16.2
Line 29 uses String method CopyTo to copy the characters of a String (string1) into a character array (characterArray). CopyTo's first argument is the index from which the method begins copying characters in the String. The second argument is the character array into which the characters are copied. The third argument is the index specifying the starting location at which the method begins placing the copied characters into the character array. The last argument is the number of characters that the method will copy from the String. Lines 3234 output the Char array contents one character at a time. |