To split according to whitespace and more, you can use regex :
func splitString(str string) []string {
re := regexp.MustCompile("[\\s\\n\\t\\r ]+") //split according to \s, \t, \r, \t and whitespace. Edit this regex for other 'conditions'
split := re.Split(str, -1)
return split
}
func main() {
var s = "It is a long\nestablished fact that a reader\nwill\nbe distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English."
var maxLen = 40
arr := splitString(s)
totalLen := 0
finalStr := ``
for _, each := range arr {
if (totalLen + len(each) > maxLen) {
fmt.Print(strings.TrimSpace(finalStr) + `...`)
break
}
totalLen += len(each)
finalStr += each + ` `
}
}
//Old 2
You can do this kind of things : Split your string in slice and loop through the slice until the total length of your string is above the max allowed length.
var s = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English."
var maxLen = 30
arr := strings.SplitAfter(s, ` `)
totalLen := 0
finalStr := ``
for _, each := range arr {
if (totalLen + len(each) > maxLen) {
fmt.Print(strings.TrimSpace(finalStr) + `...`)
break
}
totalLen += len(each)
finalStr += each
}
It is a long established fact...
//old bad answer
You have to work with strings and slices :
var s = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English."
newS := s[:30 - 3]
newS += `...`
fmt.Print(newS)
Result : It is a long established fa...