How to copy specified number of characters from a string into character array in C#?

Given a string and we have to copy number of character from given position to character array in C#
[Last updated : March 19, 2023]

Copying characters from string to character array

To copy specified number of characters from a string to character array, we use string.CopyTo() method.

Syntax

string.CopyTo(
    int sourceIndex, 
    char []destArray, 
    int destIndex , 
    int totalChar);

Where,

  • sourceIndex : It is the index of string from which we are copying characters to character array.
  • destArray : It is a character array, in which we are copying characters form string.
  • destIndex : It is index of destination character array.
  • totalChar : It specifies, how many characters will we copied.

C# program to copy characters from string to character array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      //string
      string str = "Hello, How are you ?";

      int i = 0;
      //charcater array declaration
      char[] CH = new char[11];

      //copying 11 characters from 7th index
      str.CopyTo(7, CH, 0, 11);

      //printing character by character
      for (i = 0; i < CH.Length; i++) {
        Console.Write(CH[i] + "");
      }

      Console.WriteLine();
    }
  }
}

Output

How are you

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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