To remove duplicate characters from a string in Go, you can use the following steps:
[]rune
function.string
function.Here is an example implementation:
func removeDuplicates(s string) string {
runes := []rune(s)
uniqueChars := make(map[rune]bool)
result := []rune{}
for _, char := range runes {
if !uniqueChars[char] {
uniqueChars[char] = true
result = append(result, char)
}
}
return string(result)
}
func main() {
str := "Hello, world!"
result := removeDuplicates(str)
fmt.Println(result) // Output: Helo, wrd!
}
In this example, the removeDuplicates
function takes a string as input and returns a new string with the duplicate characters removed. We convert the string to a rune slice, iterate over each character, and append it to the result slice only if it hasn't been added before. Finally, the result slice is converted back to a string.