That's cool!
Of course we could reverse rune-slice in place, leaving a 7 liner...
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r) - 1; i < j; i, j = i +1 , j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
On Friday, 28 February 2020 08:45:33 UTC, rog wrote:
>
>
>
> On Fri, 28 Feb 2020 at 08:23, Amnon Baron Cohen <[email protected]
> <javascript:>> wrote:
>
>> Here is a dumb version, that wastes loads of memory.
>>
>> func reverse(in string) string {
>> out := strings.Builder{}
>> out.Grow(len(in))
>> runes:= make([]rune, 0, len(in))
>>
>>
>> for _, r := range in {
>> runes = append(runes, r)
>> }
>>
>> You might be interested to know that this operation is built in to Go
> itself, which means you can do something like this:
>
> func Reverse(s string) string {
> runes := []rune(s)
> rev := make([]rune, 0, len(runes))
> for i := len(runes) - 1; i >= 0; i-- {
> rev = append(rev, runes[i])
> }
> return string(rev)
> }
>
> It's not even *that* much slower (about 60%). It doesn't always preserve
> the original string length though.
>
>
>
> On Saturday, 15 February 2020 16:37:15 UTC, Amarjeet Anand wrote:
>>
>> Hi
>>
>> I was wondering why isn't there built-in string reverse function. Is it
>> left intentionally because of some reason?
>>
>> Although strings are immutable in go, there are multiple ways to achieve
>> this pretty easily. But having this function inbuilt will save our time
>> because we need it quite often.
>>
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected] <javascript:>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/cae39c11-f492-4890-b0ff-332d2e51042b%40googlegroups.com
>
> <https://groups.google.com/d/msgid/golang-nuts/cae39c11-f492-4890-b0ff-332d2e51042b%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/e6239d6d-6dba-4735-902f-2eaf10ffcc38%40googlegroups.com.