Skip to content

Instantly share code, notes, and snippets.

@fredmaggiowski
Created October 19, 2016 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredmaggiowski/bfa82c3da4f038f95aeb77760d4069eb to your computer and use it in GitHub Desktop.
Save fredmaggiowski/bfa82c3da4f038f95aeb77760d4069eb to your computer and use it in GitHub Desktop.
An example of string normalisation with truncation and transformation of first letter to uppercase.
package main
import (
"bytes"
"fmt"
"unicode"
)
const MaxLength = 50
func main() {
str := "lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ac."
str = truncate(str)
fmt.Printf("%d `%s`\n", len(str), str)
}
func truncate(str string) string {
if len(str) > MaxLength {
// convert to byte slice
by := []byte(str)
// uppercase first letter
by[0] = byte(unicode.ToUpper(rune(by[0])))
// create a buffer
buff := bytes.NewBuffer(by)
// truncate
buff.Truncate(MaxLength - 3)
// convert back to string appending ellipsis dots
str = buff.String() + "..."
}
return str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment