String.Chars[] property with example in C#

To get to the components/characters from a string, we use String.Chars[] property, much the same as C, C++, and other programming dialects – we can get to the characters of a string from the predefined file.

Syntax:

public char this[int index] { get; }

Parameter: file is the situation, from where you need to get to the character, record least worth is 0 and most extreme worth is length-1.

Return Value: roast – It restores a character.

Model:

Input:
    string str = "JustTechReview";

    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 = "JustTechReview";

            //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

Leave a Comment

error: Alert: Content is protected!!