Go 語言程式清除字串緩衝區
當字串緩衝區被清除時,之前儲存在緩衝區中的所有資料都會被刪除。這可能出於各種原因,例如當您想重用緩衝區以儲存新資料時,或者當緩衝區中當前的資料不再需要時。在這裡,我們將瞭解使用 Go 程式語言清除字串緩衝區的不同技術。
語法
Reset()
使用 Reset() 方法可以丟棄所有累積的資料並將緩衝區重置為零。當建立一個新的緩衝區變數並將其分配給舊的緩衝區變數時,舊的緩衝區本質上會被新的緩衝區替換,而舊的緩衝區則被清空。
Truncate()
透過將 0 作為輸入,Truncate(0) 方法會截斷緩衝區中的所有位元組,從而清除其內容,同時保留緩衝區的容量。該方法會丟棄緩衝區中除前 n 個未讀取位元組以外的所有位元組。
演算法
步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)和 bytes 包。
步驟 2 − 使用內部函式清除緩衝區。
步驟 3 − 使用 fmt.Println() 函式將輸出列印到控制檯。
示例 1
在本例中,我們將使用 reset 方法清除字串緩衝區,該方法是用於清除字串的內建方法。
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
buffer.WriteString("Hello, alexa!") //Add string to the buffer using writestring
fmt.Println("The string before using reset method is:")
fmt.Println(buffer.String()) //print the string
buffer.Reset() //reset the string and empty it
fmt.Println("The string after using reset method is:")
fmt.Println(buffer.String()) //print empty string
}
輸出
The string before using reset method is: Hello, alexa! The string after using reset method is:
示例 2
在本例中,我們將瞭解如何使用緩衝區變數清除字串緩衝區。輸出將是列印到控制檯上的空字串。讓我們透過演算法和程式碼瞭解其執行過程。
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
buffer.WriteString("Hello, alexa!") //add the string to buffer using writestring
fmt.Println("The string before emptying it is:")
fmt.Println(buffer.String()) //print the string
buffer = bytes.Buffer{} //create a new empty buffer
fmt.Println("The string after emptying it is:")
fmt.Println(buffer.String()) //print empty string
}
輸出
The string before emptying it is: Hello, alexa! The string after emptying it is:
示例 3
在本例中,我們將瞭解如何使用 Truncate() 方法清除字串緩衝區。
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
buffer.WriteString("Hello, alexa!") //add string to the buffer using writestring
fmt.Println("The string before emptying it is:")
fmt.Println(buffer.String()) //print string
buffer.Truncate(0)
fmt.Println("The string after emptying it is:")
fmt.Println(buffer.String()) //print empty string
}
輸出
The string before emptying it is: Hello, alexa! The string after emptying it is:
結論
我們使用三個示例執行了清除字串緩衝區的程式。在第一個示例中,我們使用了 reset 方法,在第二個示例中,我們建立了一個空的緩衝區變數,在第三個示例中,我們使用了 truncate 方法來執行程式。因此,程式成功執行。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP