Use strings and bytes helpers
Use strings and bytes helpers
The strings package operates on string values. TrimSpace removes surrounding Unicode whitespace, Fields splits on whitespace, and Join combines strings with a separator. The bytes package offers corresponding helpers for byte slices. Use the representation already required by your workflow.
package main
import ( "fmt" "strings")
func main() { s := " Go\tUnicode " parts := strings.Fields(s) fmt.Println(strings.TrimSpace(s)) fmt.Println(strings.Join(parts, "-"))}TrimSpace preserves interior whitespace. Fields discards whitespace separators and returns nonempty fields. Join inserts the separator between fields. These are not general parsers for CSV or quoted fields.
Expected output:
Go UnicodeGo-UnicodeWork with byte slices
package main
import ( "bytes" "fmt")
func main() { b := []byte(" Go ") t := bytes.TrimSpace(b) t[0] = 'N' fmt.Printf("%q %q\n", b, t)}bytes.TrimSpace returns a subslice; the result can share the input backing array. Changing t changes b here. strings.TrimSpace returns immutable text. Copy a byte subslice if independent storage is needed.
Expected output:
" No " "No"Try it locally
Split " tea rice " into fields and join them with a comma.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strings and Unicode 07: Use strings and bytes helpers
Check the lesson objective before moving on.
Which helper splits text into whitespace-separated fields?
Can bytes.TrimSpace return storage shared with its input?