The Wayback Machine - https://web.archive.org/web/20240822124301/https://www.geeksforgeeks.org/c-sharp-tochararray-method/
Open In App

C# | ToCharArray() Method

Last Updated : 31 Jan, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C#, ToCharArray() is a string method. This method is used to copy the characters from a specified string in the current instance to a Unicode character array or the characters of a specified substring in the current instance to a Unicode character array. This method can be overloaded by changing the number of arguments passed to it.

Syntax:

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

Explanation:

  • public char[] ToCharArray() method will take no parameter. This method will return character array. Character array elements will contain the individual characters of the string. So basically this method will copy each character of a string to the character array. The first character of the string will be copied at index zero of the character array and the last character will be copied at index Array.Length – 1. When we create a string from the characters in a character array, then it will call String(Char[]) constructor.
  • public char[] ToCharArray(int startIndex, int length) method will take two parameters startIndex which is used to specify the starting position of the substring and its type is System.Int32. Another parameter is length which is used to specify the length of the substring and its type is System.Int32. The startIndex parameter is zero-based, means the index of the first character in the string instance can be zero.

Important Points:

  • public char[] ToCharArray(int startIndex, int length) method can give the exception ArgumentOutOfRangeException if startIndex or length is less than zero or (startIndex + length) is greater than the length of current string instance.
  • If the specified length is zero then the returned array will be empty and will have zero length. If current or this instance is null or an empty string (“”) then the returned array will be empty will have length zero.

Below are the programs to demonstrate the above Methods :

  • Program 1: To illustrate the ToCharArray() Method :




    // C# program to demonstrate
    // ToCharArray() method
    using System;
    class Geeks {
        
        // Main Method
        public static void Main()
        {
      
            String str = "GeeksForGeeks";
      
            // copy the string str to chars 
            // character array & it will start
            // copy from 'G' to 's', i.e. 
            // beginning to ending of string
            char[] chars = str.ToCharArray();
      
            Console.WriteLine("String: " + str);
            Console.Write("Character array :");
      
            // to display the resulted character array
            for (int i = 0; i < chars.Length; i++)
                Console.Write(" " + chars[i]);
        }
    }

    
    

    Output:

    String: GeeksForGeeks
    Character array : G e e k s F o r G e e k s
    
  • Program 2:To illustrate the ToCharArray(int startIndex, int length) Method :




    // C# program to demonstrate
    // ToCharArray(int startIndex, int length)
    // method
    using System;
    class Geeks {
      
        // Main Method
        public static void Main()
        {
            String str = "GeeksForGeeks";
      
            // copy the string str to chars 
            // character array & it will 
            // start copy from 'F' to 'r' i.e.
            // copy from startindex of string
            // is 5 upto (startindex+length-1) i.e.
            // 5 + (3-1) has to copy
            char[] chars1 = str.ToCharArray(5, 3);
      
            Console.WriteLine("String: " + str);
            Console.WriteLine("\nCharacter array 1:");
      
            // to display the resulted character array
            for (int i = 0; i < chars1.Length; i++)
                Console.WriteLine("Index " + i + " : " + chars1[i]);
      
            // copy the string str to chars 
            // character array & it will 
            // start copy from 'F' to 'k' i.e.
            // copy from startindex of string
            // 5 upto (startindex+length-1) i.e.
            // 5 + (7-1)
            char[] chars2 = str.ToCharArray(5, 7);
      
            Console.Write("\nCharacter array 2:");
      
            // to display the resulted character 
            // array using foreach loop
            foreach(char c in chars2)
                Console.Write(" " + c);
        }
    }

    
    

    Output:

    String: GeeksForGeeks
    
    Character array 1:
    Index 0 : F
    Index 1 : o
    Index 2 : r
    
    Character array 2: F o r G e e k
    

References :



Similar Reads

Difference between Method Overriding and Method Hiding in C#
Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called Method Overriding. In simple words, Overriding is a feature that allows a subclass or child class to provide a specific im
4 min read
C# | Uri.MakeRelativeUri(Uri) Method
Uri.MakeRelativeUri(Uri) Method is used to determine the difference between two Uri instances. Syntax: public Uri MakeRelativeUri (Uri uri); Here, it takes the URI to compare to the current URI. Return Value: If the hostname and scheme of this URI instance and uri are the same, then this method returns a relative Uri that, when appended to the curr
3 min read
Array.GetValue() Method in C# with Examples | Set - 1
Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32) Array.GetValue(Int64, Int64) Array.GetValue(Int32) Array.GetValue(Int64) Array.GetValue(Int32, Int32, Int32) Array.GetValue(Int64, Int
4 min read
C# | CharEnumerator.MoveNext() Method
CharEnumerator.MoveNext() Method is used to increments the internal index of the current CharEnumerator object to the next character of the enumerated string. Syntax: public bool MoveNext(); Return Value: This method returns the boolean value true value if the index is successfully incremented and within the enumerated string otherwise, false. Belo
2 min read
C# | Math.IEEERemainder() Method
In C#, IEEERemainder() is a Math class method which is used to return the remainder resulting from the division of a specified number by another specified number. Syntax: public static double IEEERemainder (double a, double b); Parameters: a: It is the dividend of type System.Double.b: It is the divisor of type System.Double. Return Type: This meth
2 min read
C# | Substring() Method
In C#, Substring() is a string method. It is used to retrieve a substring from the current instance of the string. This method can be overloaded by passing the different number of parameters to it as follows: String.Substring(Int32) Method String.Substring(Int32, Int32) Method String.Substring Method (startIndex) This method is used to retrieves a
3 min read
C# Program to Demonstrate the Use of Exit() Method of Environment Classhttps://origin.geeksforgeeks.org/?p=705454
Environment Class provides information about the current platform and manipulates, the current platform. The Environment class is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings informatio
3 min read
C# | IndexOfAny() Method
In C#, IndexOfAny() method is a String Method. It is used to search the specified character index present in the string which will be the first occurrence from start index. It returns index as an integer value. This method can be overloaded by changing the number of arguments passed to it. IndexOfAny Method (Char[])IndexOfAny Method (Char[], Int32)
7 min read
C# | CharEnumerator.GetType() Method
CharEnumerator.GetType() Method is used to get the type of the current instance. This method is inherited from the Object Class. Syntax: public Type GetType(); Return Value: This method returns the exact runtime type of the current instance. Below are the programs to illustrate the use of CharEnumerator.GetType() Method:+ Example 1: // C# program t
2 min read
File.GetLastWriteTimeUtc() Method in C# with Examples
File.GetLastWriteTimeUtc(String) is an inbuilt File class method which is used to return the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.Syntax: public static DateTime GetLastWriteTimeUtc (string path); Parameter: This function accepts a parameter which is illustrated below: path: Thi
2 min read
MathF.Sin() Method in C# with Examples
MathF.Sin(Single) is an inbuilt MathF class method which returns the sine of a given float value argument(specified angle). Syntax: public static float Sin (float x); Here, x is the angle(measured in radian) whose sine is to be returned and the type of this parameter is System.Single. Return Value: This method will return the sine of x of type Syst
2 min read
Double.CompareTo Method in C# with Examples
Double.CompareTo Method is used to compare the current instance to a specified object or Double object. It will return an integer which shows whether the value of the current instance is greater than, less than or equal to the value of the specified object or Double object. There are 2 methods in the overload list of this method as follows: Compare
5 min read
C# | Graphics.DrawLine() Method | Set - 1
Graphics.DrawLine() Method is used to draw a line connecting the two points specified by the coordinate pairs. There are 4 methods in the overload list of this method as follows: DrawLine(Pen, PointF, PointF) Method DrawLine(Pen, Int32, Int32, Int32, Int32) Method DrawLine(Pen, Single, Single, Single, Single) Method DrawLine(Pen, Point, Point) Meth
4 min read
UInt16.GetHashCode Method in C# with Examples
UInt16.GetHashCode method is used to get the HashCode for the current UInt16 instance. Syntax: public override int GetHashCode (); Return Value: This method returns a 32-bit signed integer hash code. Below programs illustrate the use of the above discussed-method: Example 1: // C# program to illustrate the // UInt16.GetHashCode() Method using Syste
1 min read
Stack.Peek Method in C#
This method(comes under System.Collections namespace) is used to return the object at the top of the Stack without removing it. This method is similar to the Pop method, but Peek does not modify the Stack. Syntax: public virtual object Peek (); Return Value: It returns the Object at the top of the Stack. Exception: Calling Peek() method on empty st
2 min read
C# | IsNullOrEmpty() Method
In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned "" or String.Empty (A constant for empty strings). Syntax: public static bool IsNullOrEmpty(String str) Explanation: This method w
2 min read
C# | Math.Sign() Method
In C#, Sign() is a math class method which returns an integer that specify the sign of the number. This method can be overloaded by changing the data type of the passed arguments as follows: Math.Sign(Decimal): Returns the integer that specifies the sign of a decimal number. Math.Sign(Double): Returns the integer that specifies the sign of a double
3 min read
Int64.CompareTo Method in C# with Examples
Int64.CompareTo Method is used to compare the current instance to a specified object or Int64 and returns a sign of their relative values. There are 2 methods in the overload list of this method as follows: CompareTo(Int64) Method CompareTo(Object) Method Int64.CompareTo(Int64) Method This method is used to compare the current instance to a specifi
4 min read
C# | PadRight() Method
In C#, PadRight() is a string method. This method is used to left-aligns the characters in String by padding them with spaces or specified character on the right, for a specified total length. This method can be overloaded by passing different parameters to it. String.PadRight Method(Int32)String.PadRight Method(Int32, Char)String.PadRight Method(I
4 min read
C# | EndsWith() Method
In C#, EndsWith() is a string method. This method is used to check whether the ending of the current string instance matches with a specified string or not. If it matches, then it returns the string otherwise false. Using "foreach" loop, it is possible to check many strings. This method can be overloaded by passing different type and number of argu
5 min read
C# | Char.CompareTo() Method
In C#, Char.CompareTo() is a System.Char struct method which is used to compare this instance of a specified object or value type and check whether the given instance is precedes, follow, or appears in the same position in the sort order as the specified object or value type. This method can be overloaded by passing the different type of arguments
3 min read
C# | Char.IsUpper() Method
In C#, Char.IsUpper() is a System.Char struct method which is used to check whether a Unicode character can be categorized as an uppercase letter or not. Valid uppercase letters will be the members of the UnicodeCategory: UppercaseLetter. This method can be overloaded by passing different type and number of arguments to it. Char.IsUpper(Char) Metho
3 min read
C# | BitConverter.ToSingle() Method
This method is used to returns a single-precision floating-point number converted from four bytes at a specified position in a byte array. Syntax: public static float ToSingle (byte[] value, int startIndex); Parameters: value: It is an array of bytes. startIndex: It is the starting position within value. Return Value: This method returns a single-p
6 min read
C# | ToLower() Method
In C#, ToLower() is a string method. It converts every character to lowercase (if there is a lowercase character). If a character does not have a lowercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing the different type of arguments to it. String.ToLower() Method This meth
3 min read
C# | ToUpper() Method
In C#, ToUpper() is a string method. It converts every characters to uppercase (if there is an uppercase version). If a character does not have an uppercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing different type of arguments to it. String.ToUpper() Method This method
2 min read
C# | Copy() Method
In C#, Copy() is a string method. It is used to create a new instance of String with the same value for a specified String. The Copy() method returns a String object, which is the same as the original string but represents a different object reference. To check its reference, use assignment operation, which assigns an existing string reference to a
2 min read
MathF.Truncate() Method in C# with Examples
In C#, MathF.Truncate(Single) is a MathF class method which is used to compute an integral part of a specified single number or single-precision floating-point number.Syntax: public static float Truncate (float x); Parameter: x: It is the specified number which is to be truncated and type of this parameter is System.Single. Return Type: This method
1 min read
MathF.Exp() Method in C# with Examples
In C#, Exp(Single) is a MathF class method which is used to return the e raised to the specified power. Here e is a mathematical constant whose value is approximately 2.71828. Syntax: public static float Exp (float x); Here, x is the required number of type System.Single which specifies a power. Return Type: It returns a number e raised to the powe
1 min read
C# | CopyTo() Method
In C#, CopyTo() method is a string method. It is used to copy a specified number of characters from a specified position in the string and it copies the characters of this string into a array of Unicode characters. Syntax: public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) Explanation: CopyTo() method will copi
3 min read
C# | Trim() Method
C# Trim() is a string method. This method is used to removes all leading and trailing white-space characters from the current String object. This method can be overloaded by passing arguments to it. Syntax: public string Trim() or public string Trim (params char[] trimChars) Explanation : First method will not take any parameter and the second meth
3 min read
Article Tags :
three90RightbarBannerImg