StringBuilder.Chars[] Property in C#
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:
using System;
using System.Text;
class GFG {
public static void Main(String[] args)
{
StringBuilder str =
new StringBuilder( "GeeksforGeeks" );
Console.WriteLine( "String is "
+ str.ToString());
for ( int i = 0; i < str.Length; i++) {
char ch = str[i];
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:
using System;
using System.Text;
class GFG {
public static void Main(String[] args)
{
StringBuilder str = new StringBuilder();
str.Append( "Geek" );
char ch = str[1];
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
Share your thoughts in the comments
Please Login to comment...