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 telegram 机器人小试

telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便。下面是使用golang sdk 开发telegram 机器人的经验。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 2ms