String.ToCharArray() method with example in C#

C# String.ToCharArray() technique: Here, we will find out about the ToCharArray() strategy for String class with example.

C# String.ToCharArray() Method

String.ToCharArray() technique is utilized to get the character cluster of a string, it duplicates the characters of this string to a Unicode character exhibit.

Syntax:

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

Parameter:

  • In first syntax there is no parameter, it returns character exhibit of complete string.
  • In the second syntax, there are two parameters: start_index – from where you need to duplicates the string characters to the Unicode char[], and
  • length – all outnumber of characters to be replicated.
  • 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 change over the string to characters cluster utilizing String.ToCharArray() technique:

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

Leave a Comment

error: Alert: Content is protected!!