Created
April 16, 2023 13:18
-
-
Save kahunacohen/890c117ec4fcf3356c212f0961edda0b to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"fmt" | |
"regexp" | |
"strings" | |
) | |
func reverseString(s string) string { | |
runes := []rune(s) | |
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { | |
runes[i], runes[j] = runes[j], runes[i] | |
} | |
return string(runes) | |
} | |
func reverseWords(s string) string { | |
space := regexp.MustCompile(`\s+`) | |
s = space.ReplaceAllString(s, " ") | |
ret := []string{} | |
reversedS := reverseString(s) // "rab ooF" | |
start := 0 | |
end := 0 | |
for i, r := range reversedS { | |
lastChar := i == len(reversedS)-1 | |
if r == 32 || lastChar { | |
if lastChar { | |
end = i + 1 | |
} else { | |
end = i | |
} | |
reversedWord := reversedS[start:end] | |
unreversedString := reverseString(string(reversedWord)) | |
ret = append(ret, unreversedString) | |
start = i + 1 | |
} | |
} | |
return strings.Join(ret, " ") | |
} | |
func main() { | |
fmt.Printf("**%s**", reverseWords("Hello World!")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment