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 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Golang sync.WaitGroup 的 Wait 超时处理

sync.WaitGroup 使用 `Add(1)`、`Done()`、`Wait()`组合来实现多协程等待,如果某一协程未能合理处理错误,导致无法退出,此时需要引入超时机制。下面是一种超时处理方法。...

Golang 数据库 Bolt 碎片整理

Bolt 是一个优秀、纯 Go 实现、支持 ACID 事务的嵌入式 Key/Value 数据库。但在使用过程中会有很多空间碎片。一般数据库占用的空间是元数据空间的 1.5~4 倍。Bolt 没有内置的压缩功能,需要手动压缩。...

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

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