Golang String Replace

Saturday, December 19, 2020 • 2 minutes to read

Golang2020to-the-pointgolang

Golang package strings provides Replace and ReplaceAll functions to replace the substring in the string.

Replace

Syntax

1func Replace(s, old, new string, n int) string

n is the number of first occurrence of the substring.
Replace n first occurrence of the substring.

If n < 0, then it will replace all the occurrence.

 1package main
 2
 3import (
 4	"fmt"
 5	"strings"
 6)
 7
 8func main() {
 9    str := "Th0is is an en0c0oded 0000 message"
10
11	newStr := strings.Replace(str, "0", "", 3)
12
13	fmt.Printf("Original String: %s\nAfter Replace: %s\n", str, newStr)
14
15	// n = -1
16	newStr =  strings.Replace(str, "0", "", -1)
17	fmt.Printf("After Replace with -1: %s", newStr)
18}

Output

1Original String: Th0is is an en0c0oded 0000 message
2After Replace: This is an encoded 0000 message
3After Replace with -1: This is an encoded  message

ReplaceAll

Syntax

1func ReplaceAll(s, old, new string) string
1str := "Th0is is an en0c0oded 0000 message"
2
3newStr := strings.ReplaceAll(str, "0", "")
4
5fmt.Printf("Original String: %s\nAfter Replace: %s\n", str, newStr)

Output

1Original String: Th0is is an en0c0oded 0000 message
2After Replace: This is an encoded  message

Final Words

It was always suggested to use ReplaceAll instead of Replace with -1. To support your -1 you might need to add a comment.
Keep the code self explanatory.


Golang2020to-the-pointgolang

PreviousCheck if Key Exists in Map in Golang

NextCheck if a character is a number in Golang