在Python中,我可以遍历多行字符串.
x = """\
this is
my multiline
string!"""
for line in x.splitlines():
print(line)
Run Code Online (Sandbox Code Playgroud)
Can Go也这样吗?
Ben*_*ell 17
你可以bufio.Scanner在Go中使用,它迭代来自的行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())
}
Run Code Online (Sandbox Code Playgroud)
在该示例中,for循环将继续,直到Scan()在多行字符串结尾处返回false.在每个循环中,我们打印扫描返回的行.
https://play.golang.org/p/U9_B4TsH6M
Cer*_*món 10
如果要迭代多行字符串文字,如问题所示,则使用以下代码:
for _, line := range strings.Split(strings.TrimSuffix(x, "\n"), "\n") {
fmt.Println(line)
}
Run Code Online (Sandbox Code Playgroud)
Run the code on the playground
如果要迭代从文件读取的数据,请使用bufio.Scanner.该文档有一个示例,显示如何迭代行:
scanner := bufio.NewScanner(f) // f is the *os.File
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
// handle error
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11752 次 |
| 最近记录: |