Map()
Published Sep 28, 2023
Contribute to Docs
The strings.Map()
method changes the characters of a provided string according to a given mapping function. It returns a modified copy of the original string.
Syntax
strings.Map(mappingFunc(r), s)
The strings.Map()
function takes two parameters:
mappingFunc(r)
: A function and a character (type rune) that the original character will be replaced with.s
: The given string in which the characters will be replaced.
Note: If a negative value is returned when a character is mapped, it is dropped from the string without a replacement.
Example
The following example shows the implementation of strings.Map()
:
package mainimport ("fmt""strings")func main() {mapped := func(r rune) rune {if r == 'e' {return '3'}return r}input := "Halloween"result := strings.Map(mapped, input)fmt.Println(result)}
This example results in the following output:
Hallow33n
Codebyte Example
The following example can be run and uses the strings.Map()
function to replace the character "a"
with "@"
.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Go on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Go
Learn how to use Go (Golang), an open-source programming language supported by Google!Beginner Friendly6 hours