fmt.Printf("The position of \"Marc\" is: ") fmt.Printf("%d\n", strings.Index(str, "Marc"))
fmt.Printf("The position of the first instance of \"Hi\" is: ") fmt.Printf("%d\n", strings.Index(str, "Hi")) fmt.Printf("The position of the last instance of \"Hi\" is: ") fmt.Printf("%d\n", strings.LastIndex(str, "Hi"))
fmt.Printf("The position of \"Burger\" is: ") fmt.Printf("%d\n", strings.Index(str, "Burger")) } /*output The position of "Marc" is: 8 The position of the first instance of "Hi" is: 0 The position of the last instance of "Hi" is: 14 The position of "Burger" is: -1 */
funcmain() { var str string = "Hello, how is it going, Hugo?" var manyG = "gggggggggg"
fmt.Printf("Number of H's in %s is: ", str) fmt.Printf("%d\n", strings.Count(str, "H"))
fmt.Printf("Number of double g's in %s is: ", manyG) fmt.Printf("%d\n", strings.Count(manyG, "gg")) } /*output Number of H's in Hello, how is it going, Hugo? is: 2 Number of double g’s in gggggggggg is: 5 */
重复字符串
Repeat()用于将字符串str重复n次,返回一个新的字符串。
1
strings.Repeat(s, n int) string
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package main
import ( "fmt" "strings" )
funcmain() { var origS string = "Hi there! " var newS string
newS = strings.Repeat(origS, 3) fmt.Printf("The new repeated string is: %s\n", newS) } /*output The new repeated string is: Hi there! Hi there! Hi there! */
funcmain() { var orig string = "Hey, how are you George?" var lower string var upper string
fmt.Printf("The original string is: %s\n", orig) lower = strings.ToLower(orig) fmt.Printf("The lowercase string is: %s\n", lower) upper = strings.ToUpper(orig) fmt.Printf("The uppercase string is: %s\n", upper) } /*output The original string is: Hey, how are you George? The lowercase string is: hey, how are you george? The uppercase string is: HEY, HOW ARE YOU GEORGE? */
funcmain() { str := "The quick brown fox jumps over the lazy dog" sl := strings.Fields(str) fmt.Printf("Splitted in slice: %v\n", sl) for _, val := range sl { fmt.Printf("%s - ", val) } fmt.Println() str2 := "GO1|The ABC of Go|25" sl2 := strings.Split(str2, "|") fmt.Printf("Splitted in slice: %v\n", sl2) for _, val := range sl2 { fmt.Printf("%s - ", val) } fmt.Println() str3 := strings.Join(sl2,";") fmt.Printf("sl2 joined by ;: %s\n", str3) } /*output Splitted in slice: [The quick brown fox jumps over the lazy dog] The - quick - brown - fox - jumps - over - the - lazy - dog - Splitted in slice: [GO1 The ABC of Go 25] GO1 - The ABC of Go - 25 - sl2 joined by ;: GO1;The ABC of Go;25 */
创建一个 buffer,通过 buffer.WriteString(s) 方法将字符串 s 追加到后面,最后再通过 buffer.String() 方法转换为 string
1 2 3 4 5 6 7 8 9
var buffer bytes.Buffer for { if s, ok := getNextString(); ok { //method getNextString() not shown here buffer.WriteString(s) } else { break } } fmt.Print(buffer.String(), "\n")