string - 如何在golang中椭圆截断文本?

标签 string go truncate

我希望能够干净地剪切大于一定数量字符的段落,而不会在中间剪切一个单词。

所以例如这个:

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/

相关文章:

php - 如何从文本字符串中获取 URL?

string - jsonstring 和 json 对象的区别

c# - 试图创建随机值字符串

go - AWS Cognito 的 SMS 多因素身份验证返回无效代码或身份验证状态

jenkins - 将 Go 测试输出转换为 XUnit

swift - 如何根据 RTL/LTR 连接字符串

firebase - 使用 Firebase 进行通知,获取 `app instance has been unregistered`

c# - 如何截断 .NET 字符串?

html - 如何做文本溢出 : ellipsis in reverse?

MySQL 截断 GROUP_CONCAT 函数的连接结果