TheDeveloperBlog.com

Home | Contact Us

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

<< Back to GO

Golang Fields and FieldsFunc

Use the Fields and FieldsFunc methods to separate string parts with simple syntax.
Fields. A field is separated by one or more space characters. The Fields() method in the strings package separates these into an array. It splits on groups of spaces.Strings
A key advantage. With Fields, we treat many consecutive delimiter characters as one. So several spaces is the same as a single space. This is a key advantage of Fields over Split().Split
Fields example. Here is a basic example of Fields. Please notice how the words in the value string are separated by spaces, but two or spaces may be used to separate a word.
Golang program that uses Fields method package main import ( "fmt" "strings" ) func main() { value := "Cat Dog Bird Fish" result := strings.Fields(value) // Display all fields, first field and count. fmt.Println(result) fmt.Println(result[0]) fmt.Println(len(result)) } Output [Cat Dog Bird Fish] Cat 4
FieldsFunc. This method allows us to specify the field separator as a func. The fund must receive a rune and return a bool (whether the char is a separator).

Tip: With FieldsFunc, we get the same functionality as Fields() but are not restricted to using a space separator.

Golang program that uses FieldsFunc package main import ( "fmt" "strings" ) func main() { // Return true if comma or colon char. f := func(c rune) bool { return c == ',' || c == ':' } // Separate into fields with func. fields := strings.FieldsFunc("cat,dog:bird", f) fmt.Println(fields) } Output [cat dog bird]
A review. Fields() and FieldsFunc are helpful when parsing strings that use a single delimiter character (and perhaps several in a sequence). More complex delimiters cannot be used.
© 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