Use of strings

Package main import "FMT" func main() {/* The string in Go is a slice of one byte. Strings can be created by wrapping content in "". The strings in Go are Unicode-compatible and UTF-8 encoded. A string is a collection of bytes. */ /1. Define string s1:="hello" s2:="hello world" fmt.println (s1) fmt.println (s2) //2. The length of the string is fmt.println (len(s1)) fmt.println (len(s2)) //3. To obtain a byte FMT. Println (s2 [0]) / / print for encoding a: b = 'h' : = 104 FMT. Printf (" % % % c, c, c/n ", s2 [0], a, b) / / 4. String traversal for I :=0; i<len(s2); i++ { fmt.Printf("%c",s2[i]) } fmt.Println() for _,v:=range s2{ fmt.Printf("%c",v) } fmt.Println() //5. Slice1 :=[]byte{65,66,67,68,69} s3:=string(slice1) FMT.Println(s3) s4:="abcde" slice2:=[]byte(s4) fmt.Println(slice2) //6. Println(s4) //s4[2]='B'}Copy the code

Use of strings package

import

package main import ( "fmt" "strings" ) func main() { s1:="hello wold" //1. Println(strings.Contains(s1,"llo")) //2. Bool fmt.Println(strings.containsany (s1,"abcd")) //3. Println(strings.Count(s1,"l")) //4 Starts with the prefix XX, TXT "if strings.hasprefix (s2,"2021") {fmt.println ("21 year file ")} if strings.hassuffix (s2,".txt") {fmt.println (" text document ")} //5. Println(strings.index (s1,"yyy")))// Returns -1 fmt.println (strings.indexany (s1,"abcdh"))// any character FMT. Println (strings. LastIndex (s1, "l")) / / string splicing ss1: = [] string {" ABC ", "world", "hello"} s3: = strings. Join (ss1, "-") FMT. Println (s3) / / cutting s4: = "123456789, 44" ss2: = strings. The Split (s4, ", ") for I: = 0; i<len(ss2); I ++ {FMT.Println(ss2[I])} S5 :=strings.Repeat("hello",5) fmt.Println(s5) // Replace s6:=strings.Replace(s1,"l","*",-1) fmt.Println(s6)//-1 Replace all // S7 :="hello WORLD**123" fmt.Println(strings.tolower (s7)) fmt.Println(strings.toupper (s7)) s8:=s1[0:5] fmt.Println(s1) fmt.Println(s8) fmt.Println(s1[5:]) }Copy the code