Home »
C#.Net
String.Chars[] property with example in C#
C# String.Chars[] property: Here, we are going to learn about the Chars[] property of String class with example.
Submitted by IncludeHelp, on March 17, 2019
C# String.Chars[] property
To access the elements/characters from a string, we use String.Chars[] property, just like C, C++, and other programming languages – we can access the characters of a string from the specified index.
Syntax:
public char this[int index] { get; }
Parameter: index is the position, from where you have to access the character, index minimum value is 0 and maximum value is length-1.
Return value: char – It returns a character.
Example:
Input:
string str = "IncludeHelp";
accessing characters:
str[0]: 'I'
str[1]: 'n'
str[str.Lenght-1]: 'p'
C# Example to print characters of a string using String.Chars[] property
using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//string variable declaration
string str = "IncludeHelp";
//printing first and last characters
Console.WriteLine("First character is: " + str[0]);
Console.WriteLine("Last character is: " + str[str.Length-1]);
//printing all characters based on the index
for (int loop = 0; loop < str.Length; loop++)
{
Console.WriteLine("character at {0} index is = {1}", loop, str[loop]);
}
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
First character is: I
Last character is: p
character at 0 index is = I
character at 1 index is = n
character at 2 index is = c
character at 3 index is = l
character at 4 index is = u
character at 5 index is = d
character at 6 index is = e
character at 7 index is = H
character at 8 index is = e
character at 9 index is = l
character at 10 index is = p
Reference: String.Chars[Int32] Property