我希望能够干净地剪切大于一定数量字符的段落,而不会在中间剪切一个单词。
所以例如这个:
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.
应该变成:
It is a long established fact that a reader will be distracted by the readable content ...
这是我想出的功能:
func truncateText(s string, max int) string {
if len(s) > max {
r := 0
for i := range s {
r++
if r > max {
return s[:i]
}
}
}
return s
}
但它只是粗暴地削减了文本。我想知道如何修改(或用更好的解决方案替换它)以椭圆地剪切文本?
最佳答案
slice 字符串可能会出现问题,因为 slice 适用于字节,而不是 rune 。然而,范围适用于 rune :
lastSpaceIx:=-1
len:=0
for i,r:=range str {
if unicode.IsSpace(r) {
lastSpaceIx=i
}
len++
if len>=max {
if lastSpaceIx!=-1 {
return str[:lastSpaceIx]+"..."
}
// If here, string is longer than max, but has no spaces
}
}
// If here, string is shorter than max
关于string - 如何在golang中椭圆截断文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59955085/