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:

Comments

Popular posts from this blog

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

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

Java - Blowfish Encryption and decryption Example

Java - DES Encryption and Decryption example

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

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Top 5 Java ORM tools - 2024

Java - How to Count the Number of Occurrences of Substring in a String