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 实现的基于web的文件管理-filebrowser

FileBrowser 在指定目录中提供了一个文件管理界面,可用于上传,删除,预览,重命名和编辑文件。它允许创建多个用户,每个用户都可以有自己的目录。它可以用作独立的应用程序。...

Golang Range 的性能提升Tip

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

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

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