String.ToCharArray Método

Definição

Copia os caracteres nesta instância para uma matriz de caracteres Unicode.Copies the characters in this instance to a Unicode character array.

Sobrecargas

ToCharArray(Int32, Int32)

Copia os caracteres em uma subcadeia de caracteres especificada nesta instância para uma matriz de caracteres Unicode.Copies the characters in a specified substring in this instance to a Unicode character array.

ToCharArray()

Copia os caracteres nesta instância para uma matriz de caracteres Unicode.Copies the characters in this instance to a Unicode character array.

ToCharArray(Int32, Int32)

Copia os caracteres em uma subcadeia de caracteres especificada nesta instância para uma matriz de caracteres Unicode.Copies the characters in a specified substring in this instance to a Unicode character array.

public:
 cli::array <char> ^ ToCharArray(int startIndex, int length);
public char[] ToCharArray (int startIndex, int length);
member this.ToCharArray : int * int -> char[]
Public Function ToCharArray (startIndex As Integer, length As Integer) As Char()

Parâmetros

startIndex
Int32

A posição inicial de uma subcadeia de caracteres nesta instância.The starting position of a substring in this instance.

length
Int32

O comprimento da subcadeia de caracteres nesta instância.The length of the substring in this instance.

Retornos

Char[]

Uma matriz de caracteres Unicode cujos elementos são o número de caracteres length nesta instância a partir da posição do caractere startIndex.A Unicode character array whose elements are the length number of characters in this instance starting from character position startIndex.

Exceções

startIndex ou length é menor que zero.startIndex or length is less than zero.

- ou --or-

A soma de startIndex e length é maior que o comprimento desta instância.startIndex plus length is greater than the length of this instance.

Exemplos

O exemplo a seguir converte uma substring em uma cadeia de caracteres em uma matriz de caractere e, em seguida, enumera e exibe os elementos da matriz.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 namespace System;
using namespace System::Collections;
int main()
{
   String^ str = "012wxyz789";
   array<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 );
   IEnumerator^ myEnum = arr->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Char c =  safe_cast<Char>(myEnum->Current);
      Console::WriteLine( c );
   }
}

/*
This example produces the following results:
The letters in '012wxyz789' are: 'wxyz'
Each letter in '012wxyz789' is:
w
x
y
z
*/
// 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
*/
' Sample for String.ToCharArray(Int32, Int32)
Class Sample
   
   Public Shared Sub Main()
      Dim str As String = "012wxyz789"
      Dim arr() As Char
      
      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)
      Dim c As Char
      For Each c In arr
         Console.WriteLine(c)
      Next c
   End Sub
End Class
'
'This example produces the following results:
'The letters in '012wxyz789' are: 'wxyz'
'Each letter in '012wxyz789' is:
'w
'x
'y
'z
'

Comentários

Esse método copia os caracteres em uma parte de uma cadeia de caracteres para uma matriz de caracteres.This method copies the characters in a portion of a string to a character array. Para criar uma cadeia de caracteres de um intervalo de caractere em uma matriz de caracteres, chame o String(Char[], Int32, Int32) Construtor.To create a string from a range of characters in a character array, call the String(Char[], Int32, Int32) constructor.

O startIndex parâmetro é baseado em zero.The startIndex parameter is zero-based. Ou seja, o índice do primeiro caractere na instância de cadeia de caracteres é zero.That is, the index of the first character in the string instance is zero.

Se length for zero, a matriz retornada estará vazia e terá um comprimento zero.If length is zero, the returned array is empty and has a zero length. Se essa instância for null ou uma cadeia de caracteres vazia (""), a matriz retornada estará vazia e terá um comprimento zero.If this instance is null or an empty string (""), the returned array is empty and has a zero length.

Para criar uma matriz de bytes que contenha os caracteres codificados em uma parte de uma cadeia de caracteres, crie uma instância do Encoding objeto apropriado e chame seu GetBytes(String, Int32, Int32, Byte[], Int32) método.To create a byte array that contains the encoded characters in a portion of a string, instantiate the appropriate Encoding object and call its GetBytes(String, Int32, Int32, Byte[], Int32) method. Algumas das codificações padrão disponíveis no .NET incluem:Some of the standard encodings available in .NET include:

CodificaçãoEncoding ObjetoObject
ASCIIASCII ASCIIEncoding
UTF-7UTF-7 UTF7Encoding
UTF-8UTF-8 UTF8Encoding
UTF-16UTF-16 UnicodeEncoding
UTF-32UTF-32 UTF32Encoding

Para obter mais informações, consulte codificação de caracteres no .net.For more information, see Character Encoding in .NET.

Confira também

Aplica-se a

ToCharArray()

Copia os caracteres nesta instância para uma matriz de caracteres Unicode.Copies the characters in this instance to a Unicode character array.

public:
 cli::array <char> ^ ToCharArray();
public char[] ToCharArray ();
member this.ToCharArray : unit -> char[]
Public Function ToCharArray () As Char()

Retornos

Char[]

Uma matriz de caracteres Unicode cujos elementos são os caracteres individuais desta instância.A Unicode character array whose elements are the individual characters of this instance. Se a instância for uma cadeia de caracteres vazia, a matriz retornada estará vazia e terá comprimento zero.If this instance is an empty string, the returned array is empty and has a zero length.

Exemplos

O exemplo a seguir chama o ToCharArray método para extrair os caracteres em uma cadeia de caracteres para uma matriz de caracteres.The following example calls the ToCharArray method to extract the characters in a string to a character array. Em seguida, ele exibe a cadeia de caracteres original e os elementos na matriz.It then displays the original string and the elements in the array.

using System;

public class Example
{
   public static void Main()
   {
      string s = "AaBbCcDd";
      char[] chars = s.ToCharArray();
      Console.WriteLine("Original string: {0}", s);
      Console.WriteLine("Character array:");
      for (int ctr = 0; ctr < chars.Length; ctr++)
      {
         Console.WriteLine("   {0}: {1}", ctr, chars[ctr]);
      }
   }
}

// The example displays the following output:
//     Original string: AaBbCcDd
//     Character array:
//        0: A
//        1: a
//        2: B
//        3: b
//        4: C
//        5: c
//        6: D
//        7: d
Module Example
   Public Sub Main()
      Dim s As String = "AaBbCcDd"
      Dim chars() = s.ToCharArray()
      Console.WriteLine("Original string: {0}", s)
      Console.WriteLine("Character array:")
      For ctr = 0 to chars.Length - 1
         Console.WriteLine("   {0}: {1}", ctr, chars(ctr))
      Next
   End Sub
End Module
' The example displays the following output:
'     Original string: AaBbCcDd
'     Character array:
'        0: A
'        1: a
'        2: B
'        3: b
'        4: C
'        5: c
'        6: D
'        7: d

Comentários

Esse método copia cada caractere (ou seja, cada Char objeto) em uma cadeia de caracteres para uma matriz de caracteres.This method copies each character (that is, each Char object) in a string to a character array. O primeiro caractere copiado está no índice zero da matriz de caracteres retornada; o último caractere copiado está no índice Array.Length -1.The first character copied is at index zero of the returned character array; the last character copied is at index Array.Length - 1.

Para criar uma cadeia de caracteres a partir do caractere em uma matriz de caracteres, chame o String(Char[]) Construtor.To create a string from the characters in a character array, call the String(Char[]) constructor.

Para criar uma matriz de bytes que contenha os caracteres codificados em uma cadeia de caracteres, crie uma instância do Encoding objeto apropriado e chame seu Encoding.GetBytes(String) método.To create a byte array that contains the encoded characters in a string, instantiate the appropriate Encoding object and call its Encoding.GetBytes(String) method. Algumas das codificações padrão disponíveis no .NET incluem o seguinte:Some of the standard encodings available in .NET include the following:

CodificaçãoEncoding ObjetoObject
ASCIIASCII ASCIIEncoding
UTF-7UTF-7 UTF7Encoding
UTF-8UTF-8 UTF8Encoding
UTF-16UTF-16 UnicodeEncoding
UTF-32UTF-32 UTF32Encoding

Para obter mais informações, consulte codificação de caracteres no .net.For more information, see Character Encoding in .NET.

Confira também

Aplica-se a