Skip to content

Commit

Permalink
fix: substring support utf8 character (#327)
Browse files Browse the repository at this point in the history
  • Loading branch information
liushuangls committed Mar 20, 2023
1 parent 443de35 commit de3bccf
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
6 changes: 4 additions & 2 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package lo

import (
"math/rand"
"strings"
"unicode/utf8"
)

Expand Down Expand Up @@ -36,7 +37,8 @@ func RandomString(size int, charset []rune) string {
// Substring return part of a string.
// Play: https://go.dev/play/p/TQlxQi82Lu1
func Substring[T ~string](str T, offset int, length uint) T {
size := len(str)
rs := []rune(str)
size := len(rs)

if offset < 0 {
offset = size + offset
Expand All @@ -53,7 +55,7 @@ func Substring[T ~string](str T, offset int, length uint) T {
length = uint(size - offset)
}

return str[offset : offset+int(length)]
return T(strings.Replace(string(rs[offset:offset+int(length)]), "\x00", "", -1))
}

// ChunkString returns an array of strings split into groups the length of size. If array can't be split evenly,
Expand Down
2 changes: 2 additions & 0 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ func TestSubstring(t *testing.T) {
str10 := Substring("hello", -2, 4)
str11 := Substring("hello", -4, 1)
str12 := Substring("hello", -4, math.MaxUint)
str13 := Substring("馃彔馃惗馃惐", 0, 2)

is.Equal("", str1)
is.Equal("", str2)
Expand All @@ -87,6 +88,7 @@ func TestSubstring(t *testing.T) {
is.Equal("lo", str10)
is.Equal("e", str11)
is.Equal("ello", str12)
is.Equal("馃彔馃惗", str13)
}

func TestRuneLength(t *testing.T) {
Expand Down

0 comments on commit de3bccf

Please sign in to comment.