Created
July 24, 2021 10:40
-
-
Save developer1622/caaa8d384dd7362dc83bfe2a937d43f7 to your computer and use it in GitHub Desktop.
Reverse string in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// reverse takes string 's' and reverses it and returns it. | |
// reverse does not create new string. | |
func reverse(s string) string { | |
// as strings are immutable in Golang, we have to convert | |
// to rune slice, which can be modified | |
// FYI: https://zetcode.com/golang/rune/ | |
rStr := []rune(s) | |
for i, j := 0, len(rStr)-1; i < j; i, j = i+1, j-1 { | |
// swap the letters of the string, | |
// like first with last and so on. | |
rStr[i], rStr[j] = rStr[j], rStr[i] | |
} | |
// convert the rune to string and return. | |
return string(rStr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment