Home »
C# Tutorial
C# String.Chars[] Property with Example
In this tutorial, we will learn about the C# String.Chars[] property with its usage, syntax, and examples.
By IncludeHelp Last updated : April 07, 2023
C# String.Chars[] Property
The String.Chars[] property is used to access the elements/characters from a string. 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(s)
- 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