go

Go - Safe truncate string

takakd

Takahiro Kudo

Posted on June 27, 2020

Go - Safe truncate string
package main

import (
    "fmt"
)

// Truncate string.
func TruncateString(str string, length int) string {
    if length <= 0 {
        return ""
    }

    // This code cannot support Japanese
    // orgLen := len(str)
    // if orgLen <= length {
    //     return str
    // }
    // return str[:length]

    // Support Japanese
    // Ref: Range loops https://blog.golang.org/strings
    truncated := ""
    count := 0
    for _, char := range str {
    truncated += string(char)
        count++
        if count >= length {
            break
        }
    }
    return truncated
}

// Main
func main() {
    dataList := [][]interface{} {
        {"drink", 3, "dri"},
        {"drink", 6, "drink"},
        {"drink", 0, ""},
        {"drink", -1, ""},
        {"drink", 100, "drink"},
        {"pub", 100, "pub"},
        {"こんにちは", 3, "こんに"},
    }
    for _, dl := range dataList {
        r := TruncateString(dl[0].(string), dl[1].(int))
        if r != dl[2].(string) {
            fmt.Printf("ERROR: got=%s, want=%s", r, dl[2].(string))
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

https://play.golang.org/p/QHFLlXr8v8i
https://play.golang.org/p/iakC8xxTlFI

Reference
https://play.golang.org/p/EzvhWMljku

The below code raises an error of slice.

package main

import (
    "fmt"
)

func main() {
    s := "drink"
    r := s[:20] // error
    fmt.Println(r)
}
Enter fullscreen mode Exit fullscreen mode

https://play.golang.org/p/7IfclYXADoW

💖 💪 🙅 🚩
takakd
Takahiro Kudo

Posted on June 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related