TheDeveloperBlog.com

Home | Contact Us

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

<< Back to GO

Golang unicode.IsSpace (If Char Is Whitespace)

Use the unicode.IsSpace func from the unicode package to test for space chars. Call TrimFunc.
Unicode.IsSpace. Whitespace characters often need to be handled in a different way than other characters. We need to test for spaces (and other whitespace chars).
With the unicode package, we can test for all whitespace without recalling the entire set ourselves. The unicode.IsSpace func is useful in many programs.
First example. Here we loop over the runes in a string. We use unicode.IsSpace on each rune to see if it is a space character. We also detect the ASCII code 32 (for space).

Result: The tab, newline and space characters are detected by the unicode.IsSpace func.

Golang program that uses unicode.IsSpace package main import ( "fmt" "unicode" ) func main() { value := "\tHello, friends\n" // Loop over chars in string. for _, v := range value { // Test each character to see if it is whitespace. if unicode.IsSpace(v) { fmt.Println("Is space:", v) if v == 32 { fmt.Println("ASCII code for space") } } } } Output Is space: 9 Is space: 32 ASCII code for space Is space: 10
TrimFunc, IsSpace. Consider a func like TrimFunc. The second argument required with TrimFunc is a func. We can pass unicode.IsSpace directly as the second argument.

Tip: This style of code is cleaner and less prone to bugs than implementing a custom IsSpace method ourselves.

Golang program that uses TrimFunc, unicode.IsSpace package main import ( "fmt" "unicode" "strings" ) func main() { value := "\n Hello, friends" // Use unicode.IsSpace as the func argument to TrimFunc. result := strings.TrimFunc(value, unicode.IsSpace) // Print before and after. fmt.Println("[" + value + "]") fmt.Println("[" + result + "]") } Output [ Hello, friends] [Hello, friends]
A review. The unicode module in Golang has many methods that can be used to test ranges of characters. These funcs can lead to simpler, clearer and more standard Golang code.Func
© 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