Created
September 26, 2013 05:26
-
-
Save nickpresta/6710165 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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