TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang strings.Map func

Use strings.Map to change characters in a string. Specify a func for strings.Map.
Strings.Map. Sometimes we need to modify each character (or only some characters) in a string. A for-loop could be used. But a Map() function is better.Strings
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.
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. Loops, lookup tables (with a map or slice) can be searched.

Golang program that uses strings.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 := "STARRY NIGHT, A PAINTING" fmt.Println(input) // Use Map() to run func on each rune. result := strings.Map(transform, input) fmt.Println(result) } Output STARRY NIGHT, A PAINTING ST_RRY NIGHT, _ P_INTING
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.
A summary. Simple is best. 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 in Go.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf