如果要按空格和其他字符进行分割,可以使用正则表达式:
func splitString(str string) []string {
re := regexp.MustCompile("[\\s\\n\\t\\r ]+")
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
你可以这样做:将你的字符串分割成片段,循环遍历这些片段,直到你的字符串总长度超过允许的最大长度。
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)
结果: 这是一个长期存在的事实,当一些字母被排列在一起时,它们会产生有意义的文本,而不仅仅是随机字符的组合。