📜  计算 Golang 字符串中重复单词的数量

📅  最后修改于: 2021-10-24 13:01:45             🧑  作者: Mango

给定一个字符串,任务是计算 Golang 中该特定字符串中重复的单词数。

例子:

Input: s = "She is mother of my mother."
Output: She = 1     
         is = 1
         mother = 2
         of = 1
         my = 1

为了统计重复单词的数量,首先将字符串作为输入,然后使用字符串.Fields()函数拆分字符串。函数“重复”被定义为计数得到重复的单词的数目。

下面是 Golang 中的程序,用于计算给定字符串中重复单词的数量。

// Golang program to count the number of
// repeating words in given Golang String
package main
  
import (
    "fmt"
    "strings"
)
  
func repetition(st string) map[string]int {
  
    // using strings.Field Function
    input := strings.Fields(st)
    wc := make(map[string]int)
    for _, word := range input {
        _, matched := wc[word]
        if matched {
            wc[word] += 1
        } else {
            wc[word] = 1
        }
    }
    return wc
}
  
// Main function
func main() {
    input := "betty bought the butter , the butter was bitter , " +
        "betty bought more butter to make the bitter butter better "
    for index, element := range repetition(input) {
        fmt.Println(index, "=", element)
    }
}

输出:

the = 3
, = 2
bitter = 2
to = 1
make = 1
better = 1
betty = 2
bought = 2
butter = 4
was = 1
more = 1

说明:在上面的程序中,我们首先将一个字符串作为输入,然后使用字符串.Fields()函数拆分该字符串。如果出现了相同的单词,则计数增加一个 else 值 1 返回,这意味着该单词在字符串仅出现一次。