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)
	}

}

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章