在Go语言中,切片比数组更强大、更灵活、更方便,是一种轻量级的数据结构。切片是一个可变长度的序列,它存储类似类型的元素,不允许在同一个切片中存储不同类型的元素。
在Go的字节切片中,允许使用trim()函数从给定的切片中裁剪所有的前导和尾部utf-8编码的代码点。这个函数通过切片所有在给定字符串中指定的utf -8编码的前导和尾部代码点,返回原始片的子片。如果给定的字节片中不包含指定的字符串,那么这个函数将不做任何更改返回原始的片。它是在bytes包下定义的,因此,你必须在程序中导入bytes包来访问Trim函数。
语法如下:
func Trim(ori_slice[]byte, cut_string string) []byte
这里, ori_slice是原始字节切片, 而cut_string表示要在给定切片中修剪的字符串。让我们借助给定的示例来讨论这个概念:
示例1:
//Go program to illustrate the concept
//of trim in the slice of bytes
package main
import (
"bytes"
"fmt"
)
func main() {
//Creating and initializing
//the slice of bytes
//Using shorthand declaration
slice_1 := []byte{ '!' , '!' , 'G' , 'e' , 'e' , 'k' , 's' , 'f' , 'o' , 'r' , 'G' , 'e' , 'e' , 'k' , 's' , '#' , '#' }
slice_2 := []byte{ '*' , '*' , 'A' , 'p' , 'p' , 'l' , 'e' , '^' , '^' }
slice_3 := []byte{ '%' , 'g' , 'e' , 'e' , 'k' , 's' , '%' }
//Displaying slices
fmt.Println( "Original Slice:" )
fmt.Printf( "Slice 1: %s" , slice_1)
fmt.Printf( "\nSlice 2: %s" , slice_2)
fmt.Printf( "\nSlice 3: %s" , slice_3)
//Trimming specified leading
//and trailing Unicodes points
//from the given slice of bytes
//Using Trim function
res1 := bytes.Trim(slice_1, "!#" )
res2 := bytes.Trim(slice_2, "*^" )
res3 := bytes.Trim(slice_3, "@" )
//Display the results
fmt.Printf( "New Slice:\n" )
fmt.Printf( "\nSlice 1: %s" , res1)
fmt.Printf( "\nSlice 2: %s" , res2)
fmt.Printf( "\nSlice 3: %s" , res3)
}
输出如下:
Original Slice:
Slice 1: !!srcmini##
Slice 2: **Apple^^
Slice 3: %geeks%New Slice:
Slice 1: srcmini
Slice 2: Apple
Slice 3: %geeks%
示例2:
//Go program to illustrate the concept
//of trim in the slice of bytes
package main
import (
"bytes"
"fmt"
)
func main() {
//Creating and trimming
//the slice of bytes
//Using Trim function
res1 := bytes.Trim([]byte( "****Welcome to srcmini****" ), "*" )
res2 := bytes.Trim([]byte( "!!!!Learning how to trim a slice of bytes@@@@" ), "!@" )
res3 := bytes.Trim([]byte( "^^Geek&&" ), "$" )
//Display the results
fmt.Printf( "Final Slice:\n" )
fmt.Printf( "\nSlice 1: %s" , res1)
fmt.Printf( "\nSlice 2: %s" , res2)
fmt.Printf( "\nSlice 3: %s" , res3)
}
输出如下:
Final Slice:
Slice 1: Welcome to srcmini
Slice 2: Learning how to trim a slice of bytes
Slice 3: ^^Geek&&
评论前必须登录!
注册