diff --git a/strutil/string.go b/strutil/string.go index 9ceff77..8dd0ba2 100644 --- a/strutil/string.go +++ b/strutil/string.go @@ -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) +} diff --git a/strutil/string_example_test.go b/strutil/string_example_test.go index 82a90ef..8fed392 100644 --- a/strutil/string_example_test.go +++ b/strutil/string_example_test.go @@ -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 + // 你好 +} diff --git a/strutil/string_test.go b/strutil/string_test.go index 269f6ac..26ef3fd 100644 --- a/strutil/string_test.go +++ b/strutil/string_test.go @@ -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)) +}