我想通过从任意 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
是要包含的单词数。
关于string - 如何从 golang 中的字符串制作预告片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48950692/