去readline - >串 [英] go readline -> string
本文介绍了去readline - >串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Go中执行readline字符串的惯用方法是什么?标准库中提供的原始函数看起来非常低,它们返回字节数组。有没有更容易的方式从readline函数中获取字符串?
解决方案
我写了一种方法来轻松阅读文件中的每一行。 Readln(* bufio.Reader)函数从底层bufio.Reader结构中返回一行(sans \\\
)。
// Readln从输入缓冲读取器返回一行(不含结束\\\
)
//。
//如果
//缓冲读取器出现错误,则返回错误。
func Readln(r * bufio.Reader)(string,error){
var(isPrefix bool = true
err error = nil
line,ln [] byte
)isPrefix&& amp;& amp;& amp;& amp;& err == nil {
line,isPrefix,err = r.ReadLine()
ln = append(ln,line ...)
}
返回字符串(ln),您可以使用Readln从文件中读取每一行。您可以使用Readln从文件中读取每一行。以下代码读取文件中的每一行并将每行输出到stdout。 f,err:= os.Open(fi )
if err!= nil {
fmt.Println(error opening file =,err)
os.Exit(1)
}
r:= bufio .NewReader(f)
s,e:= Readln(r)
for e == nil {
fmt.Println(s)
s,e = Readln(r)
干杯!
What is the idiomatic way to do a readline to string in Go? the raw functions provided in the standard library seem really low level, they return byte arrays. Is there any built in easier way to get a string out of a readline function?
解决方案 I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.
// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
var (isPrefix bool = true
err error = nil
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
return string(ln),err
}
You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.
f, err := os.Open(fi)
if err != nil {
fmt.Println("error opening file= ",err)
os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
fmt.Println(s)
s,e = Readln(r)
}
Cheers!
这篇关于去readline - >串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文