How to check duplicates characters from a string in Golang

In this blog post, We are going to learn ways to check duplicate characters from a string.

String is a group of any characters which are called a group of runes datatypes in Golang. It contains any characters, but sometimes duplicate characters also.

We are going to learn the below things with duplicate characters in a string.

  • Count repeated characters of a string using the String count function
  • Remove duplicate characters of a String

How to Count duplicate characters of a string using the String count function

In this example, find the count of repeated characters using the String.count() function.

Following are the steps for the program.

package main

import (
 "fmt"
 "strings"
)

func main() {
 strText := "abc aef bbbbbbbb"
 count := strings.Count(strText, "b")
 fmt.Printf("Duplicate character b count in [%v] is %d ", strText, count)

}

Output is

Duplicate character b count in [abc aef bbbbbbbb] is 9

Remove duplicate characters of a String in Golang

To remove duplicate characters from a string, follow the below steps

  • Iterate String using the range, Each iterate holds the index and currentCharacter as a rune type
  • Check currentCharacter for repeated, if not repeated, added to String.Builder.
  • Finally, Print the character to the console using the toString() method
package main

import (
 "fmt"
 "strings"
)

func main() {
value := "Hello"
var strBuilder strings.Builder
var character rune
for index, currentChar := range value {
    if currentChar != character || index == 0 {
        strBuilder.WriteRune(r)
        character = currentChar
    } else {
        continue
    }
}
fmt.Println(strBuilder.String())
}

Output:

helo