String.ToCharArray Method (Int32, Int32)

Copies the characters in a specified substring in this instance to a Unicode character array.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public char[] ToCharArray(
	int startIndex,
	int length
)

Parameters

startIndex
Type: System.Int32

The starting position of a substring in this instance.

length
Type: System.Int32

The length of the substring in this instance.

Return Value

Type: System.Char[]
A Unicode character array whose elements are the length number of characters in this instance starting from character position startIndex.

ExceptionCondition
ArgumentOutOfRangeException

startIndex or length is less than zero.

-or-

startIndex plus length is greater than the length of this instance.

The startIndex parameter is zero-based. That is, the index of the first character in the string instance is zero.

If length is zero, the returned array is empty and has a zero length. If this instance is null or an empty string (""), the returned array is empty and has a zero length.

The following example converts a substring within a string to an array of characters, then enumerates and displays the elements of the array.

// Sample for String.ToCharArray(Int32, Int32) 
using System;

class Sample {
    public static void Main() {
    string str = "012wxyz789";
    char[] arr;

    arr = str.ToCharArray(3, 4);
    Console.Write("The letters in '{0}' are: '", str);
    Console.Write(arr);
    Console.WriteLine("'");
    Console.WriteLine("Each letter in '{0}' is:", str);
    foreach (char c in arr)
        Console.WriteLine(c);
    }
}
/*
This example produces the following results:
The letters in '012wxyz789' are: 'wxyz'
Each letter in '012wxyz789' is:
w
x
y
z
*/

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft