C# 中的 StringBuilder.Chars[] 属性

2024 年 8 月 29 日 | 阅读 3 分钟

C# 的 StringBuilder 与 Java 的 StringBuilder 相当。String 对象是不可变的,这意味着它在创建后无法被修改。每次调用 System.String 类的一个函数时,都会在内存中创建一个新的 String 对象。例如,如果一个字符串 "NetworkProgramming" 占据了堆内存,将初始字符串 "NetworkProgramming" 更改为 "NP" 会在堆内存中生成一个新的字符串对象,而不是在同一内存地址上更新初始字符串。

对于重复修改字符串的操作,必须使用 StringBuilder 类。C# 引入了 StringBuilder 的概念,以防止对初始字符串进行修改、添加、删除或插入其他字符串。StringBuilder 是一个动态创建的对象。它不会在内存中创建新对象,而是根据更新的或新的字符串动态地扩展可用内存。

在提供的示例中,可以通过 StringBuilder.Chars[Int32] 属性获取或更改给定字符位置的字符。

语法

它具有以下语法:

在此语法中,in 指的是字符的位置。此属性返回指定索引处的 Unicode 字符。

异常

  • ArgumentOutOfRangeException: 设置字符时,如果索引超出了此实例的范围。
  • IndexOutOfRangeException: 检索字符时,如果索引超出了此实例的边界。

示例 1

让我们用一个例子来说明 C# 中的 Char[Int] 方法。

输出

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

示例 2

让我们用一个例子来说明 C# 中的 Char[Int] 方法。

输出

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