Golang Strings.Map() – Replace Characters from String

Golang strings.Map()

In the previous blog, we learned how to replace a string in Golang using the Replace and ReplaceAll Function. This time we will learn how we can Replace Characters from a String in Golang using the strings.Map() Function.

First of all, you should know how the Replace and ReplaceAll function works to understand the strings.Map() function.

Golang String is immutable

Once a string is declared we cannot change its characters.

Example:

s := "this is a string"
s[0] = 'T'
.\main.go:5:7: cannot assign to s[0]

we can take look at the characters of the string using index offset.

Example:

s := "this is a string"
fmt.Println(string(s[0]), string(s[8]))
t a

So, in order to change or replace the characters of the string we use the Map Function from the strings package.

Golang strings.Map()

The strings.Map() function can be used to replace or remove characters from strings.

func Map(mapping func(rune) rune, s string) string

Map Function takes two arguments, first a mapping function with the signature func(rune) rune and second a string on which actions to be done.

The mapping function is called for every character in the string and each character is replaced by the character returned by the function – or deleted if the mapping function returns a negative number.

package main

import (
	"fmt"
	"strings"
)

func main() {
	f := func(r rune) rune {
		switch r {
		case ' ':
			return '-'
		case '-':
			return ' '
		}
		return r

	}
	fmt.Println(strings.Map(f, "HeLlo go, This-is Strings Map-Function!"))

}
HeLlo-go,-This is-Strings-Map Function!

Learn more aboutĀ Golang strings.Map() Function from theĀ official Documentation.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *