StringBuilder.Chars [Int32]属性用于在此实例中在指定字符位置获取或设置字符。
用法: public char this[int index] { get; set; }
Here, the index is the position of the character.
属性值:此属性返回位置索引处的Unicode字符。
异常:
- ArgumentOutOfRangeException:设置字符时索引是否超出此实例的范围。
- IndexOutOfRangeException:获取字符时索引是否超出此实例的范围。
以下示例程序旨在说明上述属性的用法:
范例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);
}
}
}
输出:
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
范例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);
}
}
输出:
StringBuilder Object contains = Geek Character at Position 1 in StringBuilder = e
参考:
相关用法
- C# Dictionary.Values用法及代码示例
- C# Dictionary.Item[]用法及代码示例
- C# SortedDictionary.Values用法及代码示例
- C# SortedDictionary.Keys用法及代码示例
- C# SortedDictionary.Count用法及代码示例
- C# SortedDictionary.Item[]用法及代码示例
- C# Dictionary.Keys用法及代码示例
- C# Dictionary.Count用法及代码示例
- C# Queue.Count用法及代码示例
- C# Queue.IsSynchronized用法及代码示例
- C# Stack.Count用法及代码示例
- C# Stack.IsSynchronized用法及代码示例
注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 StringBuilder.Chars[] Property in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。