Home
Map
strings.Map funcUse strings.Map to change characters in a string. Specify a func for strings.Map.
Go
This page was last reviewed on Oct 10, 2022.
Strings.Map. Sometimes we need to modify each character (or only some characters) in a string. A for-loop could be used, but calling the Map() function is better.
Shows a map
With strings.Map, we apply a character transformation to each character in a string. In the func, we can use any logic—we can do lookups, or use conditional statements.
func
An example. Here we use strings.Map to replace all uppercase letter "A" runes with underscores. This example shows how to apply logic to transform each rune.
And Further branches in the conditional can be used. With loops, lookup tables (with a map or slice) can be searched.
Shows a map
package main import ( "fmt" "strings" ) func main() { transform := func(r rune) rune { // Map uppercase A to underscore. if r == 'A' { return '_' } return r } input := "A CAT" fmt.Println(input) // Use Map() to run func on each rune. result := strings.Map(transform, input) fmt.Println(result) }
A CAT _ C_T
Notes, ROT13. For things like ROT13, the strings.Map function should be used. If you need to mask certain characters (like digits or spaces) strings.Map is also effective.
ROT13
A summary. For Golang, using strings.Map eliminates a loop. And with fewer loops, it is possible for us to have fewer bugs. This func is a useful tool for string transformations in this language.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 10, 2022 (image).
Home
Changes
© 2007-2024 Sam Allen.