Go - Safe truncate string
Takahiro Kudo
Posted on June 27, 2020
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))
}
}
}
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)
}
💖 💪 🙅 🚩
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
githubcopilot AI Innovations at Microsoft Ignite 2024 What You Need to Know (Part 2)
November 29, 2024