Чтобы разделить в соответствии с пробелами и более, вы можете использовать регулярное выражение:
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 + ` `
}
}
// Старый 2
Вы можете делать такие вещи: Разделить вашу строку в срез и l oop через срез, пока общая длина вашей строки не превысит максимально допустимую длину.
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
}
Это давно установленный факт ...
// старый плохой ответ
Вы должны работать со строками и срезами:
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)
Результат: It is a long established fa...