string
Indexer, Length Property and CopyTo MethodFigure 16.2 presents
the string
indexer ([]
) for retrieving any character in a string
,
the string
property Length
, which returns a string
’s length and
the string
method CopyTo
, which copies a specified number of characters from a string
into a char
array.
Line 16 uses string
property Length
to determine the number of characters in string1
. Like arrays, string
s always know their own size.
Lines 21–24 display the characters of string1
in reverse order using the string
indexer ([]
), which treats a string
as an array of char
s and returns the character at a specific index in the string
. As with arrays, the first element of a string
has index 0.
Attempting to access a character that’s outside a string
’s bounds results in an Index-OutOfRangeException
.
Line 27 uses string
method CopyTo
to copy the characters of string1
into a character array (characterArray
). The first argument given to method CopyTo
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 30–33 output the char
array contents one character at a time.
We used a for
statement in lines 21–24 to demonstrate a string
’s Length
property and the string
indexer, using them to display the string
in reverse. That loop could have been implemented with foreach
and the Reverse
extension method as in
foreach (var element in string1.Reverse())
{
Console.Write(element);
}
Method Reverse
is one of many LINQ extension methods and requires a using
directive for the namespace System.Linq
.