From 7c1a4134b4191e87ae05d07343329e83aada6132 Mon Sep 17 00:00:00 2001 From: cuishuang Date: Fri, 7 Feb 2025 17:11:36 +0800 Subject: [PATCH] strings: add examples for Lines, SplitSeq, SplitAfterSeq, FieldsSeq and FieldsFuncSeq Change-Id: I1e5085ff2ed7f3d75ac3dc34ab72be6b55729fb7 Reviewed-on: https://go-review.googlesource.com/c/go/+/647575 Auto-Submit: Ian Lance Taylor Auto-Submit: Dmitri Shuralyov Reviewed-by: Dmitri Shuralyov Commit-Queue: Ian Lance Taylor Reviewed-by: Ian Lance Taylor Reviewed-by: Dmitri Shuralyov LUCI-TryBot-Result: Go LUCI --- src/strings/example_test.go | 90 +++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/src/strings/example_test.go b/src/strings/example_test.go index 08efcbf68f..da95d1e58e 100644 --- a/src/strings/example_test.go +++ b/src/strings/example_test.go @@ -458,3 +458,93 @@ func ExampleToValidUTF8() { // abc // abc } + +func ExampleLines() { + text := "Hello\nWorld\nGo Programming\n" + for line := range strings.Lines(text) { + fmt.Printf("%q\n", line) + } + + // Output: + // "Hello\n" + // "World\n" + // "Go Programming\n" +} + +func ExampleSplitSeq() { + s := "a,b,c,d" + for part := range strings.SplitSeq(s, ",") { + fmt.Printf("%q\n", part) + } + + // Output: + // "a" + // "b" + // "c" + // "d" +} + +func ExampleSplitAfterSeq() { + s := "a,b,c,d" + for part := range strings.SplitAfterSeq(s, ",") { + fmt.Printf("%q\n", part) + } + + // Output: + // "a," + // "b," + // "c," + // "d" +} + +func ExampleFieldsSeq() { + text := "The quick brown fox" + fmt.Println("Split string into fields:") + for word := range strings.FieldsSeq(text) { + fmt.Printf("%q\n", word) + } + + textWithSpaces := " lots of spaces " + fmt.Println("\nSplit string with multiple spaces:") + for word := range strings.FieldsSeq(textWithSpaces) { + fmt.Printf("%q\n", word) + } + + // Output: + // Split string into fields: + // "The" + // "quick" + // "brown" + // "fox" + // + // Split string with multiple spaces: + // "lots" + // "of" + // "spaces" +} + +func ExampleFieldsFuncSeq() { + text := "The quick brown fox" + fmt.Println("Split on whitespace(similar to FieldsSeq):") + for word := range strings.FieldsFuncSeq(text, unicode.IsSpace) { + fmt.Printf("%q\n", word) + } + + mixedText := "abc123def456ghi" + fmt.Println("\nSplit on digits:") + for word := range strings.FieldsFuncSeq(mixedText, unicode.IsDigit) { + fmt.Printf("%q\n", word) + } + + // Output: + // Split on whitespace(similar to FieldsSeq): + // "The" + // "quick" + // "brown" + // "fox" + // + // Split on digits: + // "abc" + // "def" + // "ghi" +} -- 2.51.0