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

go交叉编译的方法

假设开发环境是ubuntu 32 位,目标机是ubuntu 64 位,下面是交叉编译的示例...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

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

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