Created
October 19, 2016 13:07
-
-
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.
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
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