Open In App

strings.Map() Function in Golang With Examples

Last Updated : 22 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

strings.Map() Function in Golang is used to return 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:




// 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)
}


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 remove the spaces between the words of a string.




// 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)
}


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads