Go 字符串切割技巧

原文链接:http://www.zhoubotong.site/post/36.html

 标准库专门提供了一个包 strings 进行字符串的操作,随着go1.18新增的 Cut 函数,字符串处理也更加方便了。  

Cut 函数的签名如下:

func Cut(s, sep string) (before, after string, found bool)  

将字符串 s 在第一个 sep 处切割为两部分,分别存在 before 和 after 中。如果 s 中没有 sep,返回 s,"",false。

废话不多说,举个例子:

从 192.168.0.1:80 中获取 ip 和 port,直接上示例:

package main

import (
	"fmt"
	"strings"
)

func main() {
	//方法一
	addr := "192.168.0.1:80"
	pos := strings.Index(addr, ":")
	if pos == -1 {
		panic("非法地址")
	}
	ip, port := addr[:pos], addr[pos+1:]
	fmt.Println(ip, port)

	//方法二
	ip, port, ok := strings.Cut(addr, ":")
	if ok {
		fmt.Println(ip, port)
	}
	//方法三
	str := strings.Split(addr, ":")
	if len(str) == 2 {
		ip := str[0]
		port := str[1]
		fmt.Println(ip, port)
	}

}

  

posted @ 2022-03-19 16:37  周伯通之草堂  阅读(1655)  评论(0编辑  收藏  举报