strings.Map() Function in Golang With Examples
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.
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.
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.
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.