dongwo1234 2017-07-31 09:28
浏览 202
已采纳

将base64行拆分为大块

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条回答 默认 最新

  • dongshan7708 2017-07-31 09:40
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?