StringBuilder.Chars[] Property in C#

C# StringBuilder is comparable to Java StringBuilder. A String object is immutable, which means it cannot be altered after creation. Every time we call a System.String class function, a new string object is created in memory. For example, if a string "NetworkProgramming" occupies memory on the heap, altering the initial string "NetworkProgramming" to "NP" will generate a new string object on the memory of the heap rather than updating the initial string at the same memory address.

The StringBuilder class must be used for doing repetitive modifications to a string. C# introduces the StringBuilder concept to prevent altering, adding, deleting, or inserting additional strings into the initial string. StringBuilder is a dynamically created object. It does not create a new object in memory but instead dynamically extends the available memory according to the updated or new string.

The character at the given character position in this particular example can be obtained or changed using the StringBuilder.Chars[Int32] Property.

Syntax:

It has the following syntax:

In this syntax, the in refers to the character's location. This property returns the Unicode characters at the specified index.

Exceptions:

  • ArgumentOutOfRangeException: When setting a character and the index is outside this instance's constraints.
  • IndexOutOfRangeException: If the index is not inside the bounds of this instance while retrieving a character.

Example 1:

Let us take an example to illustrate the Char[Int] method in C#.

Output:

The input String is Programming Language
The Character at position 0 is P
The Character at position 1 is r
The Character at position 2 is o
The Character at position 3 is g
The Character at position 4 is r
The Character at position 5 is a
The Character at position 6 is m
The Character at position 7 is m
The Character at position 8 is i
The Character at position 9 is n
The Character at position 10 is g
The Character at position 11 is L
The Character at position 12 is a
The Character at position 13 is n
The Character at position 14 is g
The Character at position 15 is u
The Character at position 16 is a
The Character at position 17 is g
The Character at position 18 is e

Example 2:

Let us take an example to illustrate the Char[Int] method in C#.

Output:

StringBuilder Object contains = Programming
The Character at the Position 2nd StringBuilder = o





Latest Courses