feat: add Rotate for string

This commit is contained in:
dudaodong committed 2024-09-03 16:35:38 +08:00
1 parent 63216d9b1c
commit 601df5dc12
5 files changed
+152 -15

No files matched your search

+28
View File
@@ -676,3 +676,31 @@ func Shuffle(str string) string {
return string(runes)
}
// Rotate rotates the string by the specified number of characters.
// Play: todo
func Rotate(str string, shift int) string {
if shift == 0 {
return str
}
runes := []rune(str)
length := len(runes)
if length == 0 {
return str
}
shift = shift % length
if shift < 0 {
shift = length + shift
}
var sb strings.Builder
sb.Grow(length)
sb.WriteString(string(runes[length-shift:]))
sb.WriteString(string(runes[:length-shift]))
return sb.String()
}