Source file src/strings/example_test.go

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package strings_test
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  	"unicode"
    11  	"unsafe"
    12  )
    13  
    14  func ExampleClone() {
    15  	s := "abc"
    16  	clone := strings.Clone(s)
    17  	fmt.Println(s == clone)
    18  	fmt.Println(unsafe.StringData(s) == unsafe.StringData(clone))
    19  	// Output:
    20  	// true
    21  	// false
    22  }
    23  
    24  func ExampleBuilder() {
    25  	var b strings.Builder
    26  	for i := 3; i >= 1; i-- {
    27  		fmt.Fprintf(&b, "%d...", i)
    28  	}
    29  	b.WriteString("ignition")
    30  	fmt.Println(b.String())
    31  
    32  	// Output: 3...2...1...ignition
    33  }
    34  
    35  func ExampleCompare() {
    36  	fmt.Println(strings.Compare("a", "b"))
    37  	fmt.Println(strings.Compare("a", "a"))
    38  	fmt.Println(strings.Compare("b", "a"))
    39  	// Output:
    40  	// -1
    41  	// 0
    42  	// 1
    43  }
    44  
    45  func ExampleContains() {
    46  	fmt.Println(strings.Contains("seafood", "foo"))
    47  	fmt.Println(strings.Contains("seafood", "bar"))
    48  	fmt.Println(strings.Contains("seafood", ""))
    49  	fmt.Println(strings.Contains("", ""))
    50  	// Output:
    51  	// true
    52  	// false
    53  	// true
    54  	// true
    55  }
    56  
    57  func ExampleContainsAny() {
    58  	fmt.Println(strings.ContainsAny("team", "i"))
    59  	fmt.Println(strings.ContainsAny("fail", "ui"))
    60  	fmt.Println(strings.ContainsAny("ure", "ui"))
    61  	fmt.Println(strings.ContainsAny("failure", "ui"))
    62  	fmt.Println(strings.ContainsAny("foo", ""))
    63  	fmt.Println(strings.ContainsAny("", ""))
    64  	// Output:
    65  	// false
    66  	// true
    67  	// true
    68  	// true
    69  	// false
    70  	// false
    71  }
    72  
    73  func ExampleContainsRune() {
    74  	// Finds whether a string contains a particular Unicode code point.
    75  	// The code point for the lowercase letter "a", for example, is 97.
    76  	fmt.Println(strings.ContainsRune("aardvark", 97))
    77  	fmt.Println(strings.ContainsRune("timeout", 97))
    78  	// Output:
    79  	// true
    80  	// false
    81  }
    82  
    83  func ExampleContainsFunc() {
    84  	f := func(r rune) bool {
    85  		return r == 'a' || r == 'e' || r == 'i' || r == 'o' || r == 'u'
    86  	}
    87  	fmt.Println(strings.ContainsFunc("hello", f))
    88  	fmt.Println(strings.ContainsFunc("rhythms", f))
    89  	// Output:
    90  	// true
    91  	// false
    92  }
    93  
    94  func ExampleCount() {
    95  	fmt.Println(strings.Count("cheese", "e"))
    96  	fmt.Println(strings.Count("five", "")) // before & after each rune
    97  	// Output:
    98  	// 3
    99  	// 5
   100  }
   101  
   102  func ExampleCut() {
   103  	show := func(s, sep string) {
   104  		before, after, found := strings.Cut(s, sep)
   105  		fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
   106  	}
   107  	show("Gopher", "Go")
   108  	show("Gopher", "ph")
   109  	show("Gopher", "er")
   110  	show("Gopher", "Badger")
   111  	// Output:
   112  	// Cut("Gopher", "Go") = "", "pher", true
   113  	// Cut("Gopher", "ph") = "Go", "er", true
   114  	// Cut("Gopher", "er") = "Goph", "", true
   115  	// Cut("Gopher", "Badger") = "Gopher", "", false
   116  }
   117  
   118  func ExampleCutLast() {
   119  	show := func(s, sep string) {
   120  		before, after, found := strings.CutLast(s, sep)
   121  		fmt.Printf("CutLast(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
   122  	}
   123  	show("root/user/docs", "/")
   124  	show("Gopher", "/")
   125  	// Output:
   126  	// CutLast("root/user/docs", "/") = "root/user", "docs", true
   127  	// CutLast("Gopher", "/") = "Gopher", "", false
   128  }
   129  
   130  func ExampleCutPrefix() {
   131  	show := func(s, prefix string) {
   132  		after, found := strings.CutPrefix(s, prefix)
   133  		fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found)
   134  	}
   135  	show("Gopher", "Go")
   136  	show("Gopher", "ph")
   137  	// Output:
   138  	// CutPrefix("Gopher", "Go") = "pher", true
   139  	// CutPrefix("Gopher", "ph") = "Gopher", false
   140  }
   141  
   142  func ExampleCutSuffix() {
   143  	show := func(s, suffix string) {
   144  		before, found := strings.CutSuffix(s, suffix)
   145  		fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found)
   146  	}
   147  	show("Gopher", "Go")
   148  	show("Gopher", "er")
   149  	// Output:
   150  	// CutSuffix("Gopher", "Go") = "Gopher", false
   151  	// CutSuffix("Gopher", "er") = "Goph", true
   152  }
   153  
   154  func ExampleEqualFold() {
   155  	fmt.Println(strings.EqualFold("Go", "go"))
   156  	fmt.Println(strings.EqualFold("AB", "ab")) // true because comparison uses simple case-folding
   157  	fmt.Println(strings.EqualFold("ß", "ss"))  // false because comparison does not use full case-folding
   158  	// Output:
   159  	// true
   160  	// true
   161  	// false
   162  }
   163  
   164  func ExampleFields() {
   165  	fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
   166  	// Output: Fields are: ["foo" "bar" "baz"]
   167  }
   168  
   169  func ExampleFieldsFunc() {
   170  	f := func(c rune) bool {
   171  		return !unicode.IsLetter(c) && !unicode.IsNumber(c)
   172  	}
   173  	fmt.Printf("Fields are: %q", strings.FieldsFunc("  foo1;bar2,baz3...", f))
   174  	// Output: Fields are: ["foo1" "bar2" "baz3"]
   175  }
   176  
   177  func ExampleHasPrefix() {
   178  	fmt.Println(strings.HasPrefix("Gopher", "Go"))
   179  	fmt.Println(strings.HasPrefix("Gopher", "C"))
   180  	fmt.Println(strings.HasPrefix("Gopher", ""))
   181  	// Output:
   182  	// true
   183  	// false
   184  	// true
   185  }
   186  
   187  func ExampleHasSuffix() {
   188  	fmt.Println(strings.HasSuffix("Amigo", "go"))
   189  	fmt.Println(strings.HasSuffix("Amigo", "O"))
   190  	fmt.Println(strings.HasSuffix("Amigo", "Ami"))
   191  	fmt.Println(strings.HasSuffix("Amigo", ""))
   192  	// Output:
   193  	// true
   194  	// false
   195  	// false
   196  	// true
   197  }
   198  
   199  func ExampleIndex() {
   200  	fmt.Println(strings.Index("chicken", "ken"))
   201  	fmt.Println(strings.Index("chicken", "dmr"))
   202  	// Output:
   203  	// 4
   204  	// -1
   205  }
   206  
   207  func ExampleIndexFunc() {
   208  	f := func(c rune) bool {
   209  		return unicode.Is(unicode.Han, c)
   210  	}
   211  	fmt.Println(strings.IndexFunc("Hello, 世界", f))
   212  	fmt.Println(strings.IndexFunc("Hello, world", f))
   213  	// Output:
   214  	// 7
   215  	// -1
   216  }
   217  
   218  func ExampleIndexAny() {
   219  	fmt.Println(strings.IndexAny("chicken", "aeiouy"))
   220  	fmt.Println(strings.IndexAny("crwth", "aeiouy"))
   221  	// Output:
   222  	// 2
   223  	// -1
   224  }
   225  
   226  func ExampleIndexByte() {
   227  	fmt.Println(strings.IndexByte("golang", 'g'))
   228  	fmt.Println(strings.IndexByte("gophers", 'h'))
   229  	fmt.Println(strings.IndexByte("golang", 'x'))
   230  	// Output:
   231  	// 0
   232  	// 3
   233  	// -1
   234  }
   235  func ExampleIndexRune() {
   236  	fmt.Println(strings.IndexRune("chicken", 'k'))
   237  	fmt.Println(strings.IndexRune("chicken", 'd'))
   238  	// Output:
   239  	// 4
   240  	// -1
   241  }
   242  
   243  func ExampleLastIndex() {
   244  	fmt.Println(strings.Index("go gopher", "go"))
   245  	fmt.Println(strings.LastIndex("go gopher", "go"))
   246  	fmt.Println(strings.LastIndex("go gopher", "rodent"))
   247  	// Output:
   248  	// 0
   249  	// 3
   250  	// -1
   251  }
   252  
   253  func ExampleLastIndexAny() {
   254  	fmt.Println(strings.LastIndexAny("go gopher", "go"))
   255  	fmt.Println(strings.LastIndexAny("go gopher", "rodent"))
   256  	fmt.Println(strings.LastIndexAny("go gopher", "fail"))
   257  	// Output:
   258  	// 4
   259  	// 8
   260  	// -1
   261  }
   262  
   263  func ExampleLastIndexByte() {
   264  	fmt.Println(strings.LastIndexByte("Hello, world", 'l'))
   265  	fmt.Println(strings.LastIndexByte("Hello, world", 'o'))
   266  	fmt.Println(strings.LastIndexByte("Hello, world", 'x'))
   267  	// Output:
   268  	// 10
   269  	// 8
   270  	// -1
   271  }
   272  
   273  func ExampleLastIndexFunc() {
   274  	fmt.Println(strings.LastIndexFunc("go 123", unicode.IsNumber))
   275  	fmt.Println(strings.LastIndexFunc("123 go", unicode.IsNumber))
   276  	fmt.Println(strings.LastIndexFunc("go", unicode.IsNumber))
   277  	// Output:
   278  	// 5
   279  	// 2
   280  	// -1
   281  }
   282  
   283  func ExampleJoin() {
   284  	s := []string{"foo", "bar", "baz"}
   285  	fmt.Println(strings.Join(s, ", "))
   286  	// Output: foo, bar, baz
   287  }
   288  
   289  func ExampleRepeat() {
   290  	fmt.Println("ba" + strings.Repeat("na", 2))
   291  	// Output: banana
   292  }
   293  
   294  func ExampleReplace() {
   295  	fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
   296  	fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
   297  	// Output:
   298  	// oinky oinky oink
   299  	// moo moo moo
   300  }
   301  
   302  func ExampleReplaceAll() {
   303  	fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo"))
   304  	// Output:
   305  	// moo moo moo
   306  }
   307  
   308  func ExampleSplit() {
   309  	fmt.Printf("%q\n", strings.Split("a,b,c", ","))
   310  	fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
   311  	fmt.Printf("%q\n", strings.Split(" xyz ", ""))
   312  	fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
   313  	// Output:
   314  	// ["a" "b" "c"]
   315  	// ["" "man " "plan " "canal panama"]
   316  	// [" " "x" "y" "z" " "]
   317  	// [""]
   318  }
   319  
   320  func ExampleSplitN() {
   321  	fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))
   322  	z := strings.SplitN("a,b,c", ",", 0)
   323  	fmt.Printf("%q (nil = %v)\n", z, z == nil)
   324  	// Output:
   325  	// ["a" "b,c"]
   326  	// [] (nil = true)
   327  }
   328  
   329  func ExampleSplitAfter() {
   330  	fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))
   331  	// Output: ["a," "b," "c"]
   332  }
   333  
   334  func ExampleSplitAfterN() {
   335  	fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))
   336  	// Output: ["a," "b,c"]
   337  }
   338  
   339  func ExampleTitle() {
   340  	// Compare this example to the ToTitle example.
   341  	fmt.Println(strings.Title("her royal highness"))
   342  	fmt.Println(strings.Title("loud noises"))
   343  	fmt.Println(strings.Title("брат"))
   344  	// Output:
   345  	// Her Royal Highness
   346  	// Loud Noises
   347  	// Брат
   348  }
   349  
   350  func ExampleToTitle() {
   351  	// Compare this example to the Title example.
   352  	fmt.Println(strings.ToTitle("her royal highness"))
   353  	fmt.Println(strings.ToTitle("loud noises"))
   354  	fmt.Println(strings.ToTitle("брат"))
   355  	// Output:
   356  	// HER ROYAL HIGHNESS
   357  	// LOUD NOISES
   358  	// БРАТ
   359  }
   360  
   361  func ExampleToTitleSpecial() {
   362  	fmt.Println(strings.ToTitleSpecial(unicode.TurkishCase, "dünyanın ilk borsa yapısı Aizonai kabul edilir"))
   363  	// Output:
   364  	// DÜNYANIN İLK BORSA YAPISI AİZONAİ KABUL EDİLİR
   365  }
   366  
   367  func ExampleMap() {
   368  	rot13 := func(r rune) rune {
   369  		switch {
   370  		case r >= 'A' && r <= 'Z':
   371  			return 'A' + (r-'A'+13)%26
   372  		case r >= 'a' && r <= 'z':
   373  			return 'a' + (r-'a'+13)%26
   374  		}
   375  		return r
   376  	}
   377  	fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher..."))
   378  	// Output: 'Gjnf oevyyvt naq gur fyvgul tbcure...
   379  }
   380  
   381  func ExampleNewReplacer() {
   382  	r := strings.NewReplacer("<", "&lt;", ">", "&gt;")
   383  	fmt.Println(r.Replace("This is <b>HTML</b>!"))
   384  	// Output: This is &lt;b&gt;HTML&lt;/b&gt;!
   385  }
   386  
   387  func ExampleToUpper() {
   388  	fmt.Println(strings.ToUpper("Gopher"))
   389  	// Output: GOPHER
   390  }
   391  
   392  func ExampleToUpperSpecial() {
   393  	fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))
   394  	// Output: ÖRNEK İŞ
   395  }
   396  
   397  func ExampleToLower() {
   398  	fmt.Println(strings.ToLower("Gopher"))
   399  	// Output: gopher
   400  }
   401  
   402  func ExampleToLowerSpecial() {
   403  	fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Örnek İş"))
   404  	// Output: örnek iş
   405  }
   406  
   407  func ExampleTrim() {
   408  	fmt.Print(strings.Trim("¡¡¡Hello, Gophers!!!", "!¡"))
   409  	// Output: Hello, Gophers
   410  }
   411  
   412  func ExampleTrimSpace() {
   413  	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
   414  	// Output: Hello, Gophers
   415  }
   416  
   417  func ExampleTrimPrefix() {
   418  	var s = "¡¡¡Hello, Gophers!!!"
   419  	s = strings.TrimPrefix(s, "¡¡¡Hello, ")
   420  	s = strings.TrimPrefix(s, "¡¡¡Howdy, ")
   421  	fmt.Print(s)
   422  	// Output: Gophers!!!
   423  }
   424  
   425  func ExampleTrimSuffix() {
   426  	var s = "¡¡¡Hello, Gophers!!!"
   427  	s = strings.TrimSuffix(s, ", Gophers!!!")
   428  	s = strings.TrimSuffix(s, ", Marmots!!!")
   429  	fmt.Print(s)
   430  	// Output: ¡¡¡Hello
   431  }
   432  
   433  func ExampleTrimFunc() {
   434  	fmt.Print(strings.TrimFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
   435  		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
   436  	}))
   437  	// Output: Hello, Gophers
   438  }
   439  
   440  func ExampleTrimLeft() {
   441  	fmt.Print(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡"))
   442  	// Output: Hello, Gophers!!!
   443  }
   444  
   445  func ExampleTrimLeftFunc() {
   446  	fmt.Print(strings.TrimLeftFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
   447  		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
   448  	}))
   449  	// Output: Hello, Gophers!!!
   450  }
   451  
   452  func ExampleTrimRight() {
   453  	fmt.Print(strings.TrimRight("¡¡¡Hello, Gophers!!!", "!¡"))
   454  	// Output: ¡¡¡Hello, Gophers
   455  }
   456  
   457  func ExampleTrimRightFunc() {
   458  	fmt.Print(strings.TrimRightFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
   459  		return !unicode.IsLetter(r) && !unicode.IsNumber(r)
   460  	}))
   461  	// Output: ¡¡¡Hello, Gophers
   462  }
   463  
   464  func ExampleToValidUTF8() {
   465  	fmt.Printf("%s\n", strings.ToValidUTF8("abc", "\uFFFD"))
   466  	fmt.Printf("%s\n", strings.ToValidUTF8("a\xffb\xC0\xAFc\xff", ""))
   467  	fmt.Printf("%s\n", strings.ToValidUTF8("\xed\xa0\x80", "abc"))
   468  	// Output:
   469  	// abc
   470  	// abc
   471  	// abc
   472  }
   473  
   474  func ExampleLines() {
   475  	text := "Hello\nWorld\nGo Programming\n"
   476  	for line := range strings.Lines(text) {
   477  		fmt.Printf("%q\n", line)
   478  	}
   479  
   480  	// Output:
   481  	// "Hello\n"
   482  	// "World\n"
   483  	// "Go Programming\n"
   484  }
   485  
   486  func ExampleSplitSeq() {
   487  	s := "a,b,c,d"
   488  	for part := range strings.SplitSeq(s, ",") {
   489  		fmt.Printf("%q\n", part)
   490  	}
   491  
   492  	// Output:
   493  	// "a"
   494  	// "b"
   495  	// "c"
   496  	// "d"
   497  }
   498  
   499  func ExampleSplitAfterSeq() {
   500  	s := "a,b,c,d"
   501  	for part := range strings.SplitAfterSeq(s, ",") {
   502  		fmt.Printf("%q\n", part)
   503  	}
   504  
   505  	// Output:
   506  	// "a,"
   507  	// "b,"
   508  	// "c,"
   509  	// "d"
   510  }
   511  
   512  func ExampleFieldsSeq() {
   513  	text := "The quick brown fox"
   514  	fmt.Println("Split string into fields:")
   515  	for word := range strings.FieldsSeq(text) {
   516  		fmt.Printf("%q\n", word)
   517  	}
   518  
   519  	textWithSpaces := "  lots   of   spaces  "
   520  	fmt.Println("\nSplit string with multiple spaces:")
   521  	for word := range strings.FieldsSeq(textWithSpaces) {
   522  		fmt.Printf("%q\n", word)
   523  	}
   524  
   525  	// Output:
   526  	// Split string into fields:
   527  	// "The"
   528  	// "quick"
   529  	// "brown"
   530  	// "fox"
   531  	//
   532  	// Split string with multiple spaces:
   533  	// "lots"
   534  	// "of"
   535  	// "spaces"
   536  }
   537  
   538  func ExampleFieldsFuncSeq() {
   539  	text := "The quick brown fox"
   540  	fmt.Println("Split on whitespace(similar to FieldsSeq):")
   541  	for word := range strings.FieldsFuncSeq(text, unicode.IsSpace) {
   542  		fmt.Printf("%q\n", word)
   543  	}
   544  
   545  	mixedText := "abc123def456ghi"
   546  	fmt.Println("\nSplit on digits:")
   547  	for word := range strings.FieldsFuncSeq(mixedText, unicode.IsDigit) {
   548  		fmt.Printf("%q\n", word)
   549  	}
   550  
   551  	// Output:
   552  	// Split on whitespace(similar to FieldsSeq):
   553  	// "The"
   554  	// "quick"
   555  	// "brown"
   556  	// "fox"
   557  	//
   558  	// Split on digits:
   559  	// "abc"
   560  	// "def"
   561  	// "ghi"
   562  }
   563  

View as plain text