The functions that handle strings in go are mainly in the strings and Strconv packages.
Strings and strconv bag
As a basic data structure, every language has some predefined handling functions for strings. The Strings package is used in Go to perform major operations on strings.
Prefixes and suffixes
HasPrefix Checks whether the string s starts with prefix:
strings.HasPrefix(s, prefix string) bool
Copy the code
HasSuffix Checks whether string S ends with suffix:
strings.HasSuffix(s, suffix string) bool
Copy the code
The sample
package main
import (
"fmt"
"strings"
)
func main(a) {
var str string = "This is an example of a string"
fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th")
fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))}Copy the code
Output:
T/F? Does the string "This is an example of a string" have prefix Th? true
Copy the code
This example also demonstrates the use of the escape character \ and formatting strings.
String inclusion relation
Contains Determines whether the string s Contains substr:
strings.Contains(s, substr string) bool
Copy the code
Determine the position of the substring or character in the parent string (index)
Index returns the Index of the string STR in string s (the Index of the first character of STR), -1 means that string S does not contain string STR:
strings.Index(s, str string) int
Copy the code
LastIndex Returns the index of the last occurrence of STR in string s (the index of the first character of STR), -1 means that string S does not contain STR:
strings.LastIndex(s, str string) int
Copy the code
If you need to query the position of non-ASCII characters in the parent string, you are advised to use the following functions to locate characters:
strings.IndexRune(s string, r rune) int
Copy the code
Note: If ch is a non-ASCII character use strings.IndexRune(s string, Ch int) int." This method is defined in the latest version of Go as func IndexRune(s string, r rune) int. The actual use of the second parameter rune can be either rune or int, For example strings.indexrune ("chicken", 99) or strings.indexrune ("chicken", rune('k'))Copy the code
The sample
package main
import (
"fmt"
"strings"
)
func main(a) {
var str string = "Hi, I'm Marc, Hi."
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"))}Copy the code
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
Copy the code
String substitution
Replace replaces the first n strings old in string STR with string new and returns a new string, replacing all strings old with string new if n = -1:
strings.Replace(str, old, new, n) string
Copy the code
Statistics the number of occurrences of a string
Count is used to Count the number of non-overlapping occurrences of the string STR in the string s:
strings.Count(s, str string) int
Copy the code
The sample
package main
import (
"fmt"
"strings"
)
func main(a) {
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"))}Copy the code
Output:
Number of H's in Hello, how is it going, Hugo? Is: 2 Number of double g's in GGGGGGGG is: 5Copy the code
Repeated string
Repeat is used to Repeat the string s count times and return a new string:
strings.Repeat(s, count int) string
Copy the code
The sample
package main
import (
"fmt"
"strings"
)
func main(a) {
var origS string = "Hi there! "
var newS string
newS = strings.Repeat(origS, 3)
fmt.Printf("The new repeated string is: %s\n", newS)
}
Copy the code
Output:
The new repeated string is: Hi there! Hi there! Hi there!
Copy the code
Changing the case of strings
ToLower converts all Unicode characters in a string to their corresponding lowercase characters:
strings.ToLower(s) string
Copy the code
ToUpper converts all Unicode characters in a string to their corresponding uppercase characters:
strings.ToUpper(s) string
Copy the code
The sample
package main
import (
"fmt"
"strings"
)
func main(a) {
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)
}
Copy the code
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?
Copy the code
Trim string
You can use strings.trimspace (s) to strip out whitespace at the beginning and end of strings; If you want to strip out specified characters, use strings.Trim(s, “cut”) to strip out the leading and trailing cuts. The second argument to this function can contain any character. If you want to eliminate the beginning or end of the string, you can use TrimLeft or TrimRight to do so.
Split string
Strings.fields (s) will split the string into chunks using one or more whitespace characters as dynamic length delimiters and return a slice, or a slice of length 0 if the string contains only whitespace characters.
Strings.split (s, sep) is used to customize the Split symbol to Split the specified string, also returning slice.
Because both of these functions return slice, it is customary to use a for-range loop to process them (Section 7.3, p.
Concatenate slice into a string
Join is used to concatenate slice of string element type into a string using a split symbol:
strings.Join(sl []string, sep string) string
Copy the code
The sample
package main
import (
"fmt"
"strings"
)
func main(a) {
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)
}
Copy the code
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; 25Copy the code
For additional documentation on string manipulation, see the official documentation.
Reads from a string
The strings.NewReader(STR) function is used to generate a Reader, read the contents of the string, and then return a pointer to that Reader.
Read()
Read from []byte.ReadByte()
和ReadRune()
Reads the next byte or rune from the string.
String conversion to other types
String-related conversions are implemented through the Strconv package.
The package contains variables to get the number of bits of int on the operating system on which the program is running, such as strconv.intsize.
The conversion of any type T to a string is always successful.
For converting from numeric types to strings, Go provides the following functions:
strconv.Itoa(i int) string
Returns the string decimal number represented by the number I.strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) string
Converts a 64-bit floating-point number to a string, wherefmt
Presentation format (whose value can be'b'
,'e'
,'f'
或'g'
),prec
Denotes precision,bitSize
In this case, 32 indicates float32 and 64 indicates float64.
Converting a string to another type of TP is not always possible, and error parsing “… “may be thrown at runtime. : invalid argument.
For converting from a string to a number, Go provides the following functions:
strconv.Atoi(s string) (i int, err error)
Converts a string to int.strconv.ParseFloat(s string, bitSize int) (f float64, err error)
Converts a string to float64.
Taking advantage of the multi-return nature, these functions return two values, the first being the result of the conversion (if successful) and the second being the possible error. Therefore, we generally use the following form to convert from a string to another type:
val, err = strconv.Atoi(s)
Copy the code
In the following example, we ignore possible conversion errors:
The sample
package main
import (
"fmt"
"strconv"
)
func main(a) {
var orig string = "666"
var an int
var newS string
fmt.Printf("The size of ints is: %d\n", strconv.IntSize)
an, _ = strconv.Atoi(orig)
fmt.Printf("The integer is: %d\n", an)
an = an + 5
newS = strconv.Itoa(an)
fmt.Printf("The new string is: %s\n", newS)
}
Copy the code
Output:
64-bit system: The size of INts is: 64 32-bit system: The size of INts is: 32 The INTEGER is: 666 The new string is: 671Copy the code