OneBite.Dev - Coding blog in a bite size

remove a character from a string in Go

Code snippet on how to remove a character from a string in Go

package main

import (
	"fmt"
	"strings"
)

func main() {
  myString := "Hello World!"
  char := "l"
  myString = strings.Replace(myString, char, "", -1)
  fmt.Println(myString)
}

This code is written in Go language. The first line imports the libraries ‘fmt’ and ‘strings’ which provide extra functions for strings. A string called ‘myString’ containing the phrase ‘Hello World!’ is declared in the next line. The next line contains the character to be removed, in this case the letter ‘l’. Finally, the last line removes the letter ‘l’ from ‘myString’ by using the Replace function from strings package, replacing ‘l’ with an empty string. After this, the new string is printed out.

go