📜  C#中的StringBuilder.Chars []属性

📅  最后修改于: 2021-05-29 20:32:27             🧑  作者: Mango

StringBuilder.Chars [Int32]属性用于在此实例中在指定字符位置获取或设置字符。

例外情况:

  • 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

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.text.stringbuilder.chars?view=netframework-4.7.2