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 string
package main

import (
"fmt"
"strings"
)

// Main function
func 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 string
package main

import (
"fmt"
"strings"
)

// Main function
func 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)
}
}
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete