Detailed sample code for strings and strconv packages in Go language

  • 2020-06-23 00:36:37
  • OfStack

Prefixes and suffixes

HasPrefix determines whether the string s begins with prefix:


strings.HaxPrefix(s string, prefix string) bool

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  pre := "Thi"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasPrefix(str1, pre))
}

HasSuffix determines whether the string s ends with suffix:


strings.HasSuffix(s string, suffix string) bool

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  suffix := "am!"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasSuffix(str1, suffix))
}

String inclusion relation

Contains determines whether the string s contains substr:


strings.Contains(s string, substr string) bool

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
substr := "is"
  str1 := "This is a Go program!"
  fmt.Println(strings.Contains(str1, substr))
}

Determines the position of the substring or character in the parent string (index)

Index returns the index of the string substr in the string s (the index of the first character of substr), -1 means the string s does not contain the string substr:


strings.Index(s string, sbustr string) int

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  substr := "is"
  substr2 := "Hi"
  str1 := "This is a Go program!"
  fmt.Println(strings.Index(str1, substr)) // The output 2
  fmt.Println(strings.Index(str1, substr2))// The output -1
}

LastIndex returns the index of the last position in the string s (the index of the first character of substr), represented by -1

The string s does not contain the string substr:


strings.LastIndex(s string, substr string) int

Grammar:


package main
import (
  "fmt"
  "strings"
)
func main() {
  substr := "is"
  substr2 := "Hi"
  str1 := "This is a Go program!"
  fmt.Println(strings.LastIndex(str1, substr)) // The output 5
  fmt.Println(strings.LastIndex(str1, substr2))// The output -1
}

If r is a non-ES63en encoded character, the following functions are recommended for character positioning:


package main
import (
  "fmt"
  "strings"
)
func main() {
  pre := "Thi"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasPrefix(str1, pre))
}
0

The sample


package main
import (
  "fmt"
  "strings"
)
func main() {
  substr := ' In the '
  substr2 := ' day '
  str1 := " I love you China "
  fmt.Println(strings.IndexRune(str1, substr)) // The output 9
  fmt.Println(strings.IndexRune(str1, substr2))// The output -1
}
package main
import (
  "fmt"
  "strings"
)
func main() {
  substr := " In the "
  substr2 := " day "
  str1 := " I love you 𤋮 China "
  // Common Chinese characters in utf8 A majority of the 3 Bytes, some special Chinese characters ( Such as 𤋮) in utf8 A majority of the 4 Two bytes, so the output is zero 13 Rather than 12
  fmt.Println(strings.Index(str1, substr)) // The output 13
  fmt.Println(strings.Index(str1, substr2))// The output -1
}

String substitution

Replace is used to replace the previous n in the string s with the string new and return 1 new string. If n = -1, replace all the strings old with the string new:


strings.Replace(s string, old string, new string, n int) string

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  pre := "Thi"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasPrefix(str1, pre))
}
3

Count the number of occurrences of a string

Count is used to calculate the number of non-overlapping occurrences of the string substr in the string s:


package main
import (
  "fmt"
  "strings"
)
func main() {
  pre := "Thi"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasPrefix(str1, pre))
}
4

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  pre := "Thi"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasPrefix(str1, pre))
}
5

Repeated string

Repeat is used to repeat count string s and return 1 new string:


package main
import (
  "fmt"
  "strings"
)
func main() {
  pre := "Thi"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasPrefix(str1, pre))
}
6

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "This is a go program!"
  fmt.Println(strings.Repeat(s, 2)) //This is a go program!This is a go program!
}

Modify the case of the string

ToLower converts all Unicode characters in the string to the corresponding lowercase characters:


strings.ToLower(s string) string

ToUpper converts all Unicode characters in a string to the corresponding uppercase characters:


package main
import (
  "fmt"
  "strings"
)
func main() {
  pre := "Thi"
  str1 := "This is a Go program!"
  fmt.Println(strings.HasPrefix(str1, pre))
}
9

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "This is a Go program!"
  fmt.Println(strings.ToLower(s)) //this is a go program!
  fmt.Println(strings.ToUpper(s)) //THIS IS A GO PROGRAM!
}

Trim string

You can use strings.TrimSpace(s) To remove whitespace symbols at the beginning and end of a string; If you want to cull the specified character, use strings.Trim(s,cutset) To get rid of cutset at the beginning and the end. The second argument to this function can contain any character, and if you want to eliminate only the beginning or end of the string, you can use TrimLeft or TrimRight.

Remove the Spaces left and right of the string s:


strings.TrimSpace(s string) string

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  s := " ThisThis is a Go program!This "
  fmt.Println(s) // Native to print 
  fmt.Println(strings.TrimSpace(s)) // Whitespace is eliminated from the string 
}

Removes the beginning or end of a string:


strings.Trim(s string cutset string) string
strings.TrimLeft(s string, cutset string) string
strings.TrumRight(s string, cutset string) string

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "ThisThis is a Go program!This"
  fmt.Println(strings.Trim(s, "This")) // is a Go program!
  fmt.Println(strings.TrimLeft(s, "This"))//is a Go program!This
  fmt.Println(strings.TrimRight(s, "This"))//ThisThis is a Go program!
}

Split string

strings. Fields(s) will use one or more blank symbols as dynamic length separators to split the string into smaller pieces and back

Returns 1 slice, or 1 slice of length 0 if the string contains only blank symbols.


strings.Fields(s string) []string

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "This is a Go program!"
  fmt.Printf("%v\n", strings.Fields(s)) //[This is a Go program!]
}

strings.Split(s,sep) is used to customize the split symbol to split the specified string, again returning slice.

Since both functions return slice, it is customary to use the ES169en-ES170en loop to process them


strings.Split(s string, sep string) []string

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "This is a Go program!"
  result := strings.Split(s, "Go")
  fmt.Printf("%v\n", result) //[This is a  program!]
  for _, value := range result {
    fmt.Printf("%s\n", value)
  }
}

Concatenate slice to string

Join Is used to concatenate slice of element type string into a string by using a segmentation symbol:


strings.Join(a []string, sep string) string

Example:


package main
import (
  "fmt"
  "strings"
)
func main() {
  var s []string = []string{"I", "love", "you"}
  fmt.Println(strings.Join(s, " ")) //I love you
}

Reads from a string

function strings.NewReader(str) The functions used to generate an Reader and read the contents of the string, then return a pointer to that Reader, and read from other types are:

The & # 8226; Read() reads from []byte.
The & # 8226; ReadByte() and ReadRune() read the next byte or rune from the string.

String and other types of conversions

The string-related conversions are all done through the strconv package.

This package contains a variable that gets the number of digits of the int type on the operating system on which the program is running, such as ES211en.IntSize.

Any conversion of T to a string is always successful.

For converting from numeric types to strings, Go provides the following functions:

The & # 8226; strconv. Itoa(i int) string returns the decimal number of the string type represented by the number i.
The & # 8226; strconv.FormatFloat (f float64, fmt byte, prec int, bitSize int) Converts 64-bit floating-point Numbers to strings, where fmt represents the format (its value can be 'b', 'e', 'f' or 'g') and prec represents the precision, bitSize USES 32 for float32 and 64 for float64.

For converting from string to numeric types, Go provides the following functions:

The & # 8226; strconv.Atoi(s string) (i int, err error) converts the string to int type.
The & # 8226; strconv.ParseFloat (s string, bitSize int) (f float64, err error) converts the string to float64 type.

Taking advantage of the multi-return property, these functions return two values, the first is the result of the conversion (if the conversion is successful), and the second is the possible error. Therefore, we generally use the following form for the conversion from string to other types:

val, err = strconv.Atoi(s)

Example:


package main
import (
  "fmt"
  "strconv"
)
func main() {
  origin := "666"
  var an int
  var newS string
  fmt.Printf("int The number of digits of type is : %d\n", strconv.IntSize)
  an, _ = strconv.Atoi(origin)
  fmt.Println(an)
  an += 5
  newS = strconv.Itoa(an)
  fmt.Println(newS)
}

The output result is:

[

The number of digits of type int is: 64
666
671

]

conclusion


Related articles: