Proposal Details
Summary
This proposal suggests adding a new Reverse
function to the strings package in the Go standard library. The function will reverse the characters of a given string and handle Unicode characters properly by converting the input string to a slice of runes before reversing.
Motivation
Reversing a string is a common requirement in various applications, including text processing, data manipulation, and algorithm implementation. Currently, we need to implement our own string reversal functions, which can lead to inconsistencies and potential errors, especially when dealing with Unicode characters. Providing a built-in Reverse API in the strings package will offer a standardized and reliable solution for this common task.
API Signature
The Reverse
API Signature takes a string and return a new reversed string:
func Reverse(s string) string
Implementation
Here is the full proposed implementation for the API.
// Reverse returnes a copy of s but reversed
func Reverse(s string) string {
// Convert string to a rune slice
// to reverse strings containing multi-byte characters accurately
runes := []rune(s)
// Reverse the rune slice
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
// Return the string representation of the rune slice
return string(runes)
}
Thank you.
Comment From: seankhliao
Duplicate of #14777
Comment From: zigo101
I used the reverse function in tmd to build a reverse-patricia trie.
Here is a Go implementation.