當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# StringBuilder.Chars[]用法及代碼示例


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

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 StringBuilder.Chars[] Property in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。