Iterate over multiline string in Go

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

Iterate over multiline string in Go

问题

在Go语言中,你也可以迭代多行字符串。以下是一个示例:

package main

import (
	"fmt"
	"strings"
)

func main() {
	x := `this is
my multiline
string!`

	for _, line := range strings.Split(x, "\n") {
		fmt.Println(line)
	}
}

在这个示例中,我们使用反引号()来定义多行字符串。然后,我们使用strings.Split函数将字符串按行分割,并使用range`关键字迭代每一行,然后打印出来。

英文:

In Python I can iterate over a multiline string.

x = """\
this is
my multiline
string!"""

for line in x.splitlines():
    print(line)

Can Go do the same?

答案1

得分: 38

你可以在Go语言中使用bufio.Scanner,它可以迭代处理io.Reader中的每一行。下面的示例将给定的多行字符串创建为一个读取器,并将其传递给扫描器工厂函数。每次调用scanner.Scan()都会将读取器按照下一行进行分割并缓冲该行。如果没有更多的行,则返回false。调用scanner.Text()会返回缓冲的分割行。

var x string = `this is
my multiline
string`

scanner := bufio.NewScanner(strings.NewReader(x))
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

if err := scanner.Err(); err != nil {
    fmt.Printf("error occurred: %v\n", err)
}

在这个示例中,for循环会一直执行,直到Scan()在多行字符串的末尾返回false。在每次循环中,我们打印扫描器返回的行。

最后,我们检查可能发生的任何错误。

示例代码链接

英文:

You can use bufio.Scanner in Go which iterates over lines from an io.Reader. The following example creates a reader from the given multiline string and passes it to the scanner factory function. Each invocation of scanner.Scan() splits the reader on the next line and buffers the line. If there is no more lines it returns false. Calling scanner.Text() returns the buffered split.

var x string = `this is
my multiline
string`

scanner := bufio.NewScanner(strings.NewReader(x))
for scanner.Scan() {
	fmt.Println(scanner.Text())
}

if err := scanner.Err(); err != nil {
    fmt.Printf("error occurred: %v\n", err)
}

In the example, the for loop will continue until Scan() returns false at the end of the multiline string. In each loop we print the line returned by the scan.

Finally, we check for any error that might occur in the process.

https://play.golang.org/p/U9_B4TsH6M

答案2

得分: 24

如果你想遍历一个多行字符串文字,可以使用以下代码:

for _, line := range strings.Split(strings.TrimSuffix(x, "\n"), "\n") {
    fmt.Println(line)
}

在 playground 上运行代码

如果你想遍历从文件中读取的数据,请使用 bufio.Scanner。文档中有一个示例展示如何遍历每一行:

scanner := bufio.NewScanner(f) // f 是 *os.File
for scanner.Scan() {
    fmt.Println(scanner.Text()) // Println 会添加回最后的 '\n'
}
if err := scanner.Err(); err != nil {
    // 处理错误
}
英文:

If you want to iterate over a multiline string literal as shown in the question, then use this code:

for _, line := range strings.Split(strings.TrimSuffix(x, "\n"), "\n") {
	fmt.Println(line)
}

<kbd><a href="https://play.golang.org/p/8TVPHhvIPV">Run the code on the playground</a></kbd>

If you want to iterate over data read from a file, use bufio.Scanner. The documentation has an example showing how to iterate over lines:

scanner := bufio.NewScanner(f) // f is the *os.File
for scanner.Scan() {
    fmt.Println(scanner.Text()) // Println will add back the final &#39;\n&#39;
}
if err := scanner.Err(); err != nil {
   // handle error
}

答案3

得分: 3

我认为使用bufio是最好的选择,但如果你只需要拆分字符串,我认为TrimRightTrimSuffix更好,因为它可以处理任何重复的尾部换行符或回车符的组合:

package main
import "strings"

func main() {
   x := `this is
my multiline
string!
`
   for _, line := range strings.Split(strings.TrimRight(x, "\n"), "\n") {
      println(line)
   }
}

https://golang.org/pkg/strings#TrimRight

英文:

I think using bufio is the best option, but if you do need to just split a
string, I think TrimRight is better than TrimSuffix, as it could cover any
combination of repeated trailing newlines or carriage returns:

package main
import &quot;strings&quot;

func main() {
   x := `this is
my multiline
string!
`
   for _, line := range strings.Split(strings.TrimRight(x, &quot;\n&quot;), &quot;\n&quot;) {
      println(line)
   }
}

https://golang.org/pkg/strings#TrimRight

huangapple
  • 本文由 发表于 2015年10月16日 12:11:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/33162449.html
匿名

发表评论

匿名网友

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

确定