C# String.ToCharArray() Method with Example

In this tutorial, we will learn about the String.ToCharArray() method with its usage, syntax, and examples. By IncludeHelp Last updated : April 07, 2023

C# String.ToCharArray() Method

The String.ToCharArray() method is used to get the character array of a string, it copies the characters of a this string to a Unicode character array.

Syntax

char[] String.ToCharArray();
char[] String.ToCharArray(int start_index, int length);

Parameter(s)

  • In first syntax there is no parameter, it returns character array of complete string.
  • In second syntax, there are two parameters: start_index - from where you want to copies the string characters to the Unicode char[], and length – total number of characters to be copied.

Return Value

In both of the cases, it returns char[].

Example

Input:
string str = "Hello world!";
    
Function call:
char[] char_arr = str.ToCharArray();

Output:
char_arr: H e l l o   w o r l d !

Input:
string str = "Hello world!";
    
Function call:
//converting 5 characters from 6th index
char[] char_arr = str.ToCharArray(6, 5);

Output:
char_arr: w o r l d

C# example to convert string to characters array using String.ToCharArray() method

using System;
using System.Text;

namespace Test {
  class Program {
    static void Main(string[] args) {
      //string variable
      string str = "Hello world!";

      char[] char_arr = str.ToCharArray();

      Console.WriteLine("str: " + str);

      //printing char[]
      Console.WriteLine("char_arr...");
      foreach(char item in char_arr) {
        Console.Write(item + " ");
      }
      Console.WriteLine();

      //converting 5 characters from 6th index
      char_arr = str.ToCharArray(6, 5);

      //printing char[]
      Console.WriteLine("char_arr...");
      foreach(char item in char_arr) {
        Console.Write(item + " ");
      }
      Console.WriteLine();

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

str: Hello world!
char_arr...
H e l l o   w o r l d !
char_arr...
w o r l d

Reference: String.ToCharArray() Method





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.