Golang程序 清除字符串缓冲区

Golang程序 清除字符串缓冲区

当字符串缓冲区被清空时,之前存储在缓冲区内的所有数据被删除。这样做的原因有很多,包括当你想重新使用缓冲区的新鲜数据,或者当前缓冲区中的数据不再需要时。这里我们将了解使用go编程语言清除字符串缓冲区的不同技术

语法

Reset()

任何累积的数据都会被丢弃,并且使用Reset()方法将缓冲区重置为零。旧的缓冲区基本上被一个新的缓冲区所取代,当一个新的缓冲区变量被创建并分配给旧的缓冲区变量时,旧的缓冲区是空的。

Truncate()

通过给0作为输入,Truncate(0)方法截断了缓冲区中的所有字节,从而在保持缓冲区容量的同时抹去了其内容。该方法会丢弃缓冲区中除前n个未读字节以外的所有字节。

算法

  • 第1步 – 创建一个包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

在这个例子中,我们将看到如何使用buffer变量清除一个字符串缓冲区。打印出来的输出将是一个空字符串,打印在控制台。让我们通过算法和代码来看看它是如何执行的。

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方法来执行程序。因此,程序成功执行。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程