Skip to content

Instantly share code, notes, and snippets.

@nickpresta
Created September 26, 2013 05:26
Show Gist options
  • Save nickpresta/6710165 to your computer and use it in GitHub Desktop.
Save nickpresta/6710165 to your computer and use it in GitHub Desktop.
// trunecateString trunecates a string up to a maximum of length characters.
func truncateString(s string, length int) string {
l := utf8.RuneCountInString(s)
if l < length {
length = l
}
out := make([]string, length)
var ch rune
var size int
i, curr := 0, 0
for ; i < length; i++ {
ch, size = utf8.DecodeRuneInString(s[curr:])
if ch == utf8.RuneError {
out[i] = string(utf8.RuneError)
} else {
out[i] = s[curr : curr+size]
}
curr += size
}
return strings.Join(out, "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment