Related Articles

Related Articles

strings.Map() Function in Golang With Examples
  • Last Updated : 28 Apr, 2020

strings.Map() Function in Golang is used to returns a copy of the string given string with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

So whenever the user wants to make changes in a certain string, he can make use of the strings.Map() function. It replaces the character of a string with a user-desired character. If we need to mask certain characters including digits and spaces, this function can be used.

Syntax:

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

The mapping func(rune) rune parameter defines the character with which the original character needs to be replaced while the s parameter defines the original string inputted by the user.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate 
// the strings.Map() Function
package main
   
import (
    "fmt";
    "strings"
)
   
func main() {
    modified := func(r rune) rune {
        if r == 'e' {
            return '@'
        }
        return r
    }
   
    input := "Hello, Welcome to GeeksforGeeks"
    fmt.Println(input)
   
    // using the function
    result := strings.Map(modified, input)
    fmt.Println(result)
}

chevron_right


Output:

Hello, Welcome to GeeksforGeeks
H@llo, W@lcom@ to G@@ksforG@@ks

Explanation: In the above example, we have used strings.Map() function to modify a string. We have defined a variable named “modified” that replaces character ‘e’ in the string with the symbol ‘@’. Another variable named “input” takes an input string that needs transformation.

Example 2: The strings.Map() function can also be used to removes the spaces between the words of a string.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate 
// the strings.Map() Function
package main
   
import (
    "fmt";
    "strings"
)
   
func main() {
    transformed := func(r rune) rune {
           
        if r == ' ' {
            return 0
        }
        return r
    }
   
    input := "GeeksforGeeks is a computer science portal."
    fmt.Println(input)
   
    // using the function
    output := strings.Map(transformed, input)
    fmt.Println(output)
}

chevron_right


Output:

GeeksforGeeks is a computer science portal.
GeeksforGeeksisacomputerscienceportal.

Explanation: In the above example, we have used strings.Map() function to remove the spaces in between a string. We have defined a variable named “transformed” that eliminates space ‘ ‘ in the string. This is done by returning 0 at the place of spaces. Another variable named “input” takes an input string whose in-between spaces need to be removed.




My Personal Notes arrow_drop_up
Recommended Articles
Page :