将一个base64行分割成块。

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

Split a base64 line into chunks

问题

将一行的Base64字符串按照每行76个字符的方式拆分成多行的最佳方法是什么?目前我使用encoding/base64包来实现:

encoded := base64.StdEncoding.EncodeToString(data)

提前感谢您的帮助!

英文:

What is the best way to split a one line base64 into multiple lines by 76 chars. Currently I use encoding/base64 package as this:

encoded := base64.StdEncoding.EncodeToString(data)

Thank you in advance!

答案1

得分: 2

在标准库中没有对此提供支持。你需要自己实现一个。

一个简单的实现可以是这样的:

func split(s string, size int) []string {
    ss := make([]string, 0, len(s)/size+1)
    for len(s) > 0 {
        if len(s) < size {
            size = len(s)
        }
        ss, s = append(ss, s[:size]), s[size:]
    }
    return ss
}

这个函数会循环直到字符串被消耗完,每次迭代从开头截取 size 个字符(字节)。

请注意,这个函数适用于 base64 文本,因为它只使用与 UTF-8 编码形式中的字节一一对应的字符(这是 Go 在内存中存储字符串的方式)。如果你想在任意字符串上使用它,切片操作可能会破坏有效的 UTF-8 序列,并且分块的大小不一定是 size 个字符。

测试一下:

s := strings.Repeat("1", 2*76+3)
for _, chunk := range split(s, 76) {
    fmt.Println(chunk)
}

输出结果(在 Go Playground 上尝试):

1111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111
111
英文:

There is no support for this in the standard lib. You have to make one yourself.

A simple implementation can be like this:

func split(s string, size int) []string {
	ss := make([]string, 0, len(s)/size+1)
	for len(s) &gt; 0 {
		if len(s) &lt; size {
			size = len(s)
		}
		ss, s = append(ss, s[:size]), s[size:]

	}
	return ss
}

This loops until the string is consumed, and in each iteration cuts of size chars (bytes) from the beginning.

Note that this works on base64 texts as that only uses characters which map 1-to-1 to bytes in the UTF-8 encoded form (which is how Go stores strings in memory). If you would want to use this on arbitrary strings, slicing could break valid UTF-8 sequences, and also chunks would not necessarily be size characters.

Testing it:

s := strings.Repeat(&quot;1&quot;, 2*76+3)
for _, chunk := range split(s, 76) {
	fmt.Println(chunk)
}

Output (try it on the Go Playground):

1111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111
111

huangapple
  • 本文由 发表于 2017年7月31日 17:28:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/45412089.html
匿名

发表评论

匿名网友

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

确定