GolangNote

Golang笔记

golang 截取中文不出现乱码的方法

Permalink

golang 截取中文不出现乱码的方法

Go: 截取中文不出现乱码的方法
1
2
3
4
5
6
7
8
9
10
package main

import "fmt"

func main() {
	s := "我是中文,标点符号,中文字符截取"
	s2 := []rune(s)
	fmt.Println(len(s), len(s2))
	fmt.Println(string(s2[:4]))
}

截取文章内容摘要时经常作这样的判断

Go: 截取实例
1
2
3
4
5
6
7
contentRune := []rune(article.Content)
if len(contentRune) > 150 {
    contentRune := []rune(article.Content)
    item.Des = string(contentRune[:150])
} else {
    item.Des = article.Content
}

本文网址: https://golangnote.com/topic/194.html 转摘请注明来源

Related articles

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

Write a Comment to "golang 截取中文不出现乱码的方法"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms