从golang中的字符串中删除重复的单词

问题描述 投票:0回答:3

我在 golang 中有一个字符串:

“嘿嘿嘿嘿嘿嘿嘿”

我想删除重复的单词,只保留一个来获得这个:

“嗨嗨你好”

go
3个回答
3
投票

有多种方法可以实现这一目标。其一是这样的:

import "strings"

func Dedup(input string) string {
    unique := []string{}

    words := strings.Split(input, " ")
    for _, word := range words {
        // If we alredy have this word, skip.
        if contains(unique, word) {
            continue
        }
 
        unique = append(unique, word)
    }
 
    return strings.Join(unique, " ")
}
 
func contains(strs []string, str string) bool {
    for _, s := range strs {
        if s == str {
            return true
        }
    }
    return false
}

1
投票
package main
import "fmt"

func removeDuplicates(arr []string) []string {
    words_string := map[string]bool{}
    for i:= range arr {
        words_string[arr[i]] = true
    }
    desired_output := []string{}  // Keep all keys from the map into a slice.
    for j, _ := range words_string {
        desired_output = append(desired_output, j)
    }
    return desired_output
}
func main() {
    arr := []string{"hi", "hi", "hi", "ho", "ho", "hello"}
    fmt.Println(arr)
    desired_output := removeDuplicates(arr)  // Remove the duplicates
    fmt.Println(desired_output)
}

0
投票

func removeDuplicates(text string) 字符串 {

var result string
uniqueText := map[string]bool{}
words := strings.Fields(text)
for _, word := range words {
    if uniqueText[word] {
        continue
    }

    uniqueText[word] = true
    result += word + " "
}

return strings.TrimSuffix(result, " ")

}

© www.soinside.com 2019 - 2024. All rights reserved.