dongwo1234
dongwo1234
2017-07-31 09:28

将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 dongshan7708 4年前

    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
    
    点赞 评论 复制链接分享

相关推荐