Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Find and delete a substring in Go (Golang)

Posted on March 22, 2023March 22, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

strings package of GO provides a ReplaceAll method that can be used to replace all non-overlapping instances of a given substring with a new substring. We can use this method to delete a substring by providing the replacement of the substring to be deleted as an empty string

Below is the signature of the function. The function will replace all non-overlapping instances of old with new in string s. To delete a substring we can supply that substring as old and new as an empty string

func ReplaceAll(s, old, new string) string

Let’s look at the working code

Code:

package main
import (
"fmt"
"strings"
)
func main() {
res = strings.ReplaceAll("abcabcabcdef", "ab", "")
fmt.Println(res)
}

Output:

cccdef

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2023 Welcome To Golang By Example | Design: Web XP