Golang strings.Map() Function with Examples

Golang | strings.Map() Function: Here, we are going to learn about the Map() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 19, 2021

strings.Map()

The Map() function is an inbuilt function of strings package which is used to get a copy of the given string with all its characters modified according to the mapping function. It accepts two parameters – a mapping function and a string. And, returns the modified string.

Note: If the mapping function returns a negative value, the character is dropped from the string with no replacement.

Syntax:

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

Parameter(s):

  • mapping func : A mapping function for checking and modifying the characters of the string.
  • str : The main string to be modified through the mapping function.

Return Value:

The return type of Map() function is a string, it returns a copy of the given string with all its characters modified according to the mapping function.

Example 1:

// Golang program to demonstrate the
// example of strings.Map() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	// function to invert the case i.e.
	// uppercase character to lowercase character
	// and vice versa

	invertCase := func(r rune) rune {
		switch {
		case r >= 'A' && r <= 'Z':
			return r + 32
		case r >= 'a' && r <= 'z':
			return r - 32
		}
		return r
	}
	fmt.Println(strings.Map(invertCase, "Hello, world! How are you?"))
}

Output:

hELLO, WORLD! hOW ARE YOU?

Example 2:

// Golang program to demonstrate the
// example of strings.Map() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	// converts semicolon (;) to the comma (,)
	modify := func(r rune) rune {
		if r == ';' {
			return ','
		}
		return r
	}

	str := "Hello; world! You; there?"
	fmt.Println(str)

	// using the function
	result := strings.Map(modify, str)
	fmt.Println(result)
}

Output:

Hello; world! You; there?
Hello, world! You, there?

Golang strings Package Functions »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.