Go Language - Program to find the duplicate words in a string
Hello everyone, today we need to find out the duplicate words present in the string and print those words.
Example 1: Program to find the duplicate words in a given string
//Program to find the duplicate words in a stringpackage main
import ( "fmt" "strings")
// Main functionfunc main() {
str := "hola hello hi hola good sleep hello hi night morning"
//Converts the string into lowercase strl := strings.ToLower(str)
//Split the string into words words := strings.Split(strl, " ") fmt.Println("Duplicate words in a given string are, \n")
for i := 0; i < len(words); i++ { count := 1 for j := i + 1; j < len(words); j++ { if words[i] == words[j] { count++ //Set words[j] to 0 to avoid printing visited word words[j] = "0" } }
//Displays the duplicate word if count is greater than 1 if count > 1 && words[i] != "0" { fmt.Println(words[i]) } }}
Output:
Example 2: Program to count duplicate words from given String
//Program to find the duplicate words in a stringpackage main
import ( "fmt" "strings")
// Main functionfunc main() {
str := "hola hello hi hola good sleep hello hi night morning hi"
//Converts the string into lowercase strl := strings.ToLower(str)
//Split the string into words words := strings.Split(strl, " ") fmt.Println("Duplicate words in a given string are, \n")
for i := 0; i < len(words); i++ { count := 1 for j := i + 1; j < len(words); j++ { if words[i] == words[j] { count++ //Set words[j] to 0 to avoid printing visited word words[j] = "0" } }
//Displays the duplicate word if count is greater than 1 if count > 1 && words[i] != "0" { fmt.Println(words[i], count) } }}