如何从Reader中获取字符串?

huangapple go评论77阅读模式
英文:

How to get a string from a Reader?

问题

strings模块中,有一个名为NewReader的函数,用于从字符串创建一个Reader对象。

要从strings.Reader中获取/读取字符串,可以使用Read方法。通过调用Read方法并提供一个字节数组作为参数,可以将字符串内容读取到该字节数组中。读取的字节数可以通过返回值获取。以下是一个示例代码:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello, World!"
	reader := strings.NewReader(str)

	// 创建一个字节数组,用于存储读取的字符串内容
	buf := make([]byte, len(str))

	// 读取字符串内容到字节数组中
	n, err := reader.Read(buf)
	if err != nil {
		fmt.Println("读取错误:", err)
		return
	}

	// 将字节数组转换为字符串并打印输出
	fmt.Println(string(buf[:n]))
}

在上面的示例中,我们首先使用strings.NewReader函数创建了一个strings.Reader对象,然后创建了一个与字符串长度相同的字节数组buf。接下来,我们调用Read方法将字符串内容读取到buf中,并通过string(buf[:n])将字节数组转换为字符串。最后,我们打印输出了读取到的字符串内容。

英文:

In the strings module, there is a function func NewReader(s string) *Reader to create a Reader from a string.

How can you get/read the string from the strings.Reader?

答案1

得分: 2

你可以使用ioutil.ReadAll

bytes, err := ioutil.ReadAll(r)
// 这里进行错误处理
s := string(bytes)
英文:

You can use ioutil.ReadAll :

bytes, err := ioutil.ReadAll(r)
// err management here
s := string(bytes)

huangapple
  • 本文由 发表于 2013年9月4日 01:27:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/18598148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定