string - 如何从 golang 中的字符串制作预告片?

标签 string go

我想通过从任意 utf8 输入字符串 content 中删除前几个单词(除以空格)来制作预告片。 我想到的是这个:

runes := []rune(content)
teaser := string(runes[0:75]) 

问题是上面的代码在中间切断了单词。我想要的是在(比如说第十个)字的末尾剪掉,以制作漂亮的预告片。

我怎样才能做到这一点?

最佳答案

func teaser(s string, wordCount int) string {
    words := strings.Fields(s)

    if len(words) < wordCount {
        wordCount = len(words)
    }

    return strings.Join(words[:wordCount], " ")
}

... 其中 s 是您的完整字符串,wordCount 是要包含的单词数。

Playground

关于string - 如何从 golang 中的字符串制作预告片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48950692/

相关文章:

c# - 字符串中的特殊字符.Replace

arrays - 如何使用 while 循环将字符串值存储在数组的特定索引中

python - 如何从 Python 中的字符串中删除所有空格

C程序计算输入文件中的总字数

javascript - 为什么在 Nodejs 中比较两个字符串时 '===' 比逐字符比较慢

go - cgo 不导出导入包中的函数

macos - 安装程序如何在 Mac OSX 上设置 PATH 变量?

go - 在 Go 中给定多个 URL 参数的过程图像

去映射大量键的性能不佳

google-app-engine - 在 golang 上执行 post 请求以获取 uber 身份验证不起作用