Strings Package Split Join And Fields
Cut lines apart with strings.Fields and Split, reassemble with Join, and finish with ReplaceAll, HasPrefix, and ToUpper.
Code
package main
import (
"fmt"
"strings"
)
func main() {
line := " deploy api, worker, cron "
// Fields 按连续空白切分并丢弃空串,Split 则保留空段
fields := strings.Fields(line)
fmt.Printf("fields: %q\n", fields)
parts := strings.Split(strings.TrimSpace(line), ",")
for i, p := range parts {
parts[i] = strings.TrimSpace(p)
}
fmt.Printf("split: %q\n", parts)
// Join 是 Split 的逆操作;ReplaceAll 全量替换
fmt.Println("joined:", strings.Join(fields, " | "))
fmt.Println("replaced:", strings.ReplaceAll(line, "worker", "scheduler"))
fmt.Println("has prefix deploy:", strings.HasPrefix(strings.TrimSpace(line), "deploy"))
fmt.Println("upper fields:", strings.ToUpper(fields[0]))
}What the code does
Strings Package Split Join And Fields reduces to the function main.
Iteration happens inside for i, p := range parts — everything outside it runs once.
Applying it
The run emits 6 labeled sections — fields:, split:, joined:, replaced:, has prefix deploy:, upper fields: — one per step.
Statements that matter
for i, p := range parts {
parts[i] = strings.TrimSpace(p)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Strings Package Split Join And Fields print when run?
- No setup needed: run the file and look for labeled lines like `fields:`, `split:`, `joined:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.