Home »
.Net »
C# Programs
How to copy specified number of characters from a string into character array in C#?
C# - Copy specified number of characters from a string into character array: Here, we will learn how we can copy number of character from given position of the string into character array in C#.Net using string.CopyTo() method?
Given a string and we have to copy number of character from given position to character array in C#.Net.
To copy specified number characters of string to character array .NET framework provides built in method, which is:
string.CopyTo(int sourceIndex, char []destArray, int destIndex , int totalChar);
Here,
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.
Consider the program:
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 »