Menu Close

Go – Map() function in strings package in go

Here, We will learn about Map() function in strings package in go.  Map() function is used to get a copy of the string with all its characters modified according to the mapping function in go golang.

Function prototype:

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

Input Parameters:

mapping - Function to manipulate string
s - string

Return value:

Map() function in strings package returns
a copy of the string s with all its
characters modified according to the mapping
function.
If any character from string will not get
manipulated by mapping function, Then It returns
negative value.

Example with code:

package main

import (
  "fmt"
  "strings"
)

func validate_fun(r rune) rune {

  switch {
    case r >= 'A' && r <= 'Z':
      return 'A' + (r - 'A' + 10) % 26

    case r >= 'a' && r <= 'z':
      return 'a' + (r -'a' + 10) % 26		
  }
  return r
}

func main() {

  str := "Hello all"
  s := strings.Map(validate_fun, str)
  fmt.Println(s)

  str = ""
  s = strings.Map(validate_fun, str)
  fmt.Println(s)

  str = "12345"
  s = strings.Map(validate_fun, str)
  fmt.Println(s)

  str = "-123.455"
  s = strings.Map(validate_fun, str)
  fmt.Println(s)

  str = "Hello all @@##$$"
  s = strings.Map(validate_fun, str)
  fmt.Println(s)
}

Output:

Rovvy kvv

12345
-123.455
Rovvy kvv @@##$$

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, strings

Leave a Reply

Your email address will not be published.

Contact Us