英文:
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) > 0 {
if len(s) < 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("1", 2*76+3)
for _, chunk := range split(s, 76) {
fmt.Println(chunk)
}
Output (try it on the Go Playground):
1111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111
111
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论