通过


StringBuilder.Clear 方法

定义

从当前 StringBuilder 实例中删除所有字符。

public:
 System::Text::StringBuilder ^ Clear();
public System.Text.StringBuilder Clear();
member this.Clear : unit -> System.Text.StringBuilder
Public Function Clear () As StringBuilder

返回

一个对象,其 Length 值为 0(零)。

示例

以下示例使用字符串实例化对象 StringBuilder ,调用 Clear 该方法,然后追加一个新字符串。

using System;
using System.Text;

public class Class1
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder("This is a string.");
      Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);
      
      sb.Clear();
      Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);

      sb.Append("This is a second string.");
      Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);
   }
}
// The example displays the following output:
//       This is a string. (17 characters)
//        (0 characters)
//       This is a second string. (24 characters)
open System.Text

let sb = StringBuilder "This is a string."
printfn $"{sb} ({sb.Length} characters)"

sb.Clear() |> ignore
printfn $"{sb} ({sb.Length} characters)"

sb.Append "This is a second string." |> ignore
printfn $"{sb} ({sb.Length} characters)"

// The example displays the following output:
//       This is a string. (17 characters)
//        (0 characters)
//       This is a second string. (24 characters)
Imports System.Text

Module Example
   Public Sub Main()
      Dim sb As New StringBuilder("This is a string.")
      Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length)
      
      sb.Clear()
      Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length)

      sb.Append("This is a second string.")
      Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length)
   End Sub            
End Module
' The example displays the following output:
'       This is a string. (17 characters)
'        (0 characters)
'       This is a second string. (24 characters)

注解

Clear 是一种便利方法,等效于将 Length 当前实例的属性设置为 0(零)。

适用于