1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-07 06:02:27 +08:00

feat: add Substring function

This commit is contained in:
dudaodong
2022-12-29 19:55:40 +08:00
parent b5f7b0e670
commit 1dc5e8ac23
3 changed files with 59 additions and 0 deletions

View File

@@ -281,3 +281,27 @@ func SplitEx(s, sep string, removeEmptyString bool) []string {
return ret
}
// Substring returns a substring of the specified length starting at the specified offset position.
func Substring(s string, offset int, length uint) string {
rs := []rune(s)
size := len(rs)
if offset < 0 {
offset = size + offset
if offset < 0 {
offset = 0
}
}
if offset > size {
return ""
}
if length > uint(size)-uint(offset) {
length = uint(size - offset)
}
str := string(rs[offset : offset+int(length)])
return strings.Replace(str, "\x00", "", -1)
}

View File

@@ -337,3 +337,27 @@ func ExampleUnwrap() {
// foo*
// *foo*
}
func ExampleSubstring() {
result1 := Substring("abcde", 1, 3)
result2 := Substring("abcde", 1, 5)
result3 := Substring("abcde", -1, 3)
result4 := Substring("abcde", -2, 2)
result5 := Substring("abcde", -2, 3)
result6 := Substring("你好,欢迎你", 0, 2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
fmt.Println(result6)
// Output:
// bcd
// bcde
// e
// de
// de
// 你好
}

View File

@@ -287,3 +287,14 @@ func TestSplitEx(t *testing.T) {
assert.Equal([]string{"a", "b", "c", ""}, SplitEx("a = b = c = ", " = ", false))
assert.Equal([]string{"a", "b", "c"}, SplitEx("a = b = c = ", " = ", true))
}
func TestSubstring(t *testing.T) {
assert := internal.NewAssert(t, "TestSubstring")
assert.Equal("bcd", Substring("abcde", 1, 3))
assert.Equal("bcde", Substring("abcde", 1, 5))
assert.Equal("e", Substring("abcde", -1, 3))
assert.Equal("de", Substring("abcde", -2, 2))
assert.Equal("de", Substring("abcde", -2, 3))
assert.Equal("你好", Substring("你好,欢迎你", 0, 2))
}