GolangNote

Golang笔记

Golang 按行分割字符串方法总汇

Permalink

Go 语言按行分割字符串很方便,这里作一下汇总,根据不同场景使用不同方法。

使用 strings.Split

内置函数 strings.Split 的基本使用

Go: strings.Split
1
2
3
4
s := strings.Split("a,b,c,d", ",")
fmt.Println(s)
// Output: [a b c d]

按行分割

Go: strings.Split
1
2
3
4
5
s := strings.Split(`a\nb\nc\nd`, `\n`)
// s := strings.Split("a\\nb\\nc\\nd", "\n")
fmt.Println(s)
// Output: [a b c d]

考虑到 windows 系统换行符,可以这么写

Go: strings.Split windows
1
strings.Split(strings.ReplaceAll(windows, "\r\n", "\n"), "\n")

使用正则分割

Go: 按行分割字符串
1
2
zp := regexp.MustCompile(`[\t\n\f\r]`)
lines := zp.Split(yourStr, -1)

使用 strings.Fields

使用 strings.Fields 按行分割

Go: strings.Fields
1
2
3
4
s := strings.Fields(" a \t b \n")
fmt.Println(s)
// Output: [a b]

使用 bufio.Scanner

使用 bufio.Scanner 按行分割

Go: bufio.Scanner
1
2
3
4
5
6
7
8
9
10
11
12
13
import (
    "bufio"
    "strings"
)

func SplitLines(s string) []string {
    var lines []string
    sc := bufio.NewScanner(strings.NewReader(s))
    for sc.Scan() {
        lines = append(lines, sc.Text())
    }
    return lines
}

本文网址: https://golangnote.com/topic/289.html 转摘请注明来源

Related articles

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

Write a Comment to "Golang 按行分割字符串方法总汇"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms