Open In App

StringBuilder.Chars[] Property in C#

Improve
Improve
Like Article
Like
Save
Share
Report

StringBuilder.Chars[Int32] Property is used to get or set the character at the specified character position in this instance.

Syntax: public char this[int index] { get; set; }
Here, the index is the position of the character.

Property Value: This property returns the Unicode character at position index.

Exceptions:

  • ArgumentOutOfRangeException: If the index is outside the bounds of this instance while setting a character.
  • IndexOutOfRangeException: If the index is outside the bounds of this instance while getting a character.

Below programs illustrate the use of the above-discussed property:

Example 1:




// C# program demonstrate
// the Chars[Int32] Property
using System;
using System.Text;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str = 
         new StringBuilder("GeeksforGeeks");
  
        // print string
        Console.WriteLine("String is "
                     + str.ToString());
  
        // loop through string
        // and print every Character
        for (int i = 0; i < str.Length; i++) {
  
            // get char at position i
            char ch = str[i];
  
            // print char
            Console.WriteLine("Char at position "
                              + i + " is " + ch);
        }
    }
}


Output:

String is GeeksforGeeks
Char at position 0 is G
Char at position 1 is e
Char at position 2 is e
Char at position 3 is k
Char at position 4 is s
Char at position 5 is f
Char at position 6 is o
Char at position 7 is r
Char at position 8 is G
Char at position 9 is e
Char at position 10 is e
Char at position 11 is k
Char at position 12 is s

Example 2:




// C# program demonstrate
// the Chars[Int32] Property
using System;
using System.Text;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // create a StringBuilder object
        StringBuilder str = new StringBuilder();
  
        // add the String to StringBuilder Object
        str.Append("Geek");
  
        // get char at position 1
        char ch = str[1];
  
        // print the result
        Console.WriteLine("StringBuilder Object"
                        + " contains = " + str);
  
        Console.WriteLine("Character at Position 1"
                     + " in StringBuilder = " + ch);
    }
}


Output:

StringBuilder Object contains = Geek
Character at Position 1 in StringBuilder = e

Reference:



Last Updated : 28 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads