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

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example