前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >根据首尾字符串截取中间字符串

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

原创
作者头像
仁扬
发布2023-08-03 00:02:42
2220
发布2023-08-03 00:02:42
举报
文章被收录于专栏:仁扬笔记

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

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

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

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

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

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

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

```html

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

```

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

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

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

```golang

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 哈哈):

```golang

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/](https://imlht.com/archives/412/)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档