根据首尾字符串截取中间字符串

发布时间 2023-08-03 00:08:18作者: 仁扬

这段时间工作的需求多了不少,文章开始越来越水了。

实在抱歉,时间真的很仓促。

本次分享的是一个函数——根据首尾字符串截取中间的字符串。

虽然这个函数非常简单,但是真的很好用!也很常用!

比如 “我今天真的很高兴” 这句话,要把 今天 截取出来:

常规的方式是 strings.Index 出位置,然后根据字符串(今天)的长度,返回词的内容。

如果是 HTML 呢?比如获取链接地址:

<a href='https://m.baidu.com/'>跳转到百度</a>

这个时候你还想用 strings.Index 吗?

我是不想用的!太麻烦了。而用我的这个函数,就很方便了!

直接 StringCut(s, "href='", "'", false) 就可以轻松拿到链接地址!非常通用,无需关心越界问题。

func StringCut(s, begin, end string, withBegin bool) string {
	beginPos := strings.Index(s, begin)
	if beginPos == -1 {
		return ""
	}
	s = s[beginPos+len(begin):]
	endPos := strings.Index(s, end)
	if endPos == -1 {
		return ""
	}
	result := s[:endPos]
	if withBegin {
		return begin + result
	} else {
		return result
	}
}

附带单元测试,包含了很多例子,如果还有特殊情况,欢迎补充(找 bug 哈哈):

func TestStringCut(t *testing.T) {
	type args struct {
		s         string
		begin     string
		end       string
		withBegin bool
	}
	tests := []struct {
		name string
		args args
		want string
	}{
		{"test", args{"", "a", "d", false}, ""},
		{"test", args{"abcd", "", "d", false}, "abc"},
		{"test", args{"abcd", "a", "", false}, ""},
		{"test", args{"abcd", "e", "d", false}, ""},
		{"test", args{"abcd", "a", "f", false}, ""},
		{"test", args{"abcd", "a", "d", false}, "bc"},
		{"test", args{"abcd", "a", "d", true}, "abc"},
		{"test", args{"abcd", "abcd", "", true}, "abcd"},
		{"test", args{"abcd", "", "abcd", true}, ""},
		{"test", args{"abcd", "ab", "cd", false}, ""},
		{"test", args{"abcd", "abcd", "e", false}, ""},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := StringCut(tt.args.s, tt.args.begin, tt.args.end, tt.args.withBegin); got != tt.want {
				t.Errorf("StringCut() = %v, want %v", got, tt.want)
			}
		})
	}
}

注:复制粘贴不要忘了 import "strings"

时间不早了,得赶紧睡觉了,晚安。


文章来源于本人博客,发布于 2022-12-19,原文链接:https://imlht.com/archives/412/