mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-17 11:12:28 +08:00
feat: add Substring function
This commit is contained in:
@@ -281,3 +281,27 @@ func SplitEx(s, sep string, removeEmptyString bool) []string {
|
|||||||
|
|
||||||
return ret
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -337,3 +337,27 @@ func ExampleUnwrap() {
|
|||||||
// foo*
|
// foo*
|
||||||
// *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
|
||||||
|
// 你好
|
||||||
|
}
|
||||||
|
|||||||
@@ -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 = ", " = ", false))
|
||||||
assert.Equal([]string{"a", "b", "c"}, SplitEx("a = b = c = ", " = ", true))
|
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))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user