Preface
Go Also like C Language family languages are the same , Use double quotation marks to declare strings .
Go Strings can be used Double quotes (" ") perhaps The quotation marks (\ \
) To create . Double quotes are used to create parseable strings , But it can't be used to refer to multiple lines , This is how most strings are defined .
Backquotes are used to create native strings , These strings can consist of multiple lines . Mostly used for multi line messages ,HTML And regular expressions .
For example, we declare a string like this :
package main
import "fmt"
func main() {
hello_Chinese := " Hello! "
hello_English := "Hello"
hello_Japanese := "こんにちは"
hello_French := "Bonjour"
fmt.Println(hello_Chinese)
fmt.Println(hello_English)
fmt.Println(hello_Japanese)
fmt.Println(hello_French)
longString := `
Hello, my friend!
.This is a long string`
fmt.Println(longString)
}
Run the above code , We can see Go It can also support non English characters , such as “ Hello! ”、“こんにちは”:
$ go run hello.go
Hello!
Hello
こんにちは
Bonjour
Hello, my friend!
.This is a long string
String splicing
It is inevitable that some string appending or splicing functions will appear in the development process ,Go The language provides a string pair plus sign “
- It is inevitable that some string appending or splicing functions will appear in the process ,Go The language provides a string pair plus sign “+” Support for , Use “ + ” Operator concatenates two strings :
str1 := "Hello "
str2 := "world"
str3 := str1 + str2
fmt.Println(str3) // Hello world
If you want to create a long parseable string variable , But I don't want to write a long line in the code , You can also use “
- To create a long parseable string variable , But I don't want to write a long line in the code , You can also use “ + ” Splices connect these fragments .
It should be noted that ,Go The string of a language is immutable , But they support “ += ” Append operator . This method of string concatenation is easy to read , Very suitable for simple situations . however , although Go We are indeed allowed to use +( or +=) Operators connect strings , But it is not the most effective way . It is best to use only when adding few strings , Not in the hot code path .
text := "the very things that in the moment dampen our moods " +
"can later be sources of intense gratification"
text += " and delight."
fmt.Println(text)
In most cases , Built in fmt.Sprintf
Function is a better choice to build a string .
str4 := fmt.Sprintf("%s %s", str1, str2)
fmt.Println(str4) // Hello world
Be careful :“+” No. does not support the addition and splicing of different types of variables .
Use fmt Package to format the string
"%s" Sequence is a special placeholder , It tells Sprintf Function inserts a string at this position . There are other sequences that are not strings , such as :
- "%d" Represents an integer
- "%f" Represents a floating point number
- or "%v" Means to leave it to determine the type .
These sequences allow us to add numbers and other types to strings without casting .
grammar | meaning |
fmt.Errorf(format, args…) | Returns a string containing the given format string and args Wrong value of parameter |
fmt.Fprint(writer, args…) | By format %v Non strings separated by spaces will args write in writer in , Returns the number of bytes written and a value of error perhaps nil The wrong value of |
fmt.Fprintf(writer, format, args…) | In string format format take args Parameter write writer, Returns the number of bytes written and a value of error perhaps nil The wrong value of |
fmt.Fprintln(writer, args…) | By format %v Non strings separated by spaces will args write in writer, Returns the number of bytes written and a value of error perhaps nil The wrong value of |
fmt.Print(format, args…) | By format %v Non strings separated by spaces will args write in os.Stdout, Returns the number of bytes written and a value of error perhaps nil The wrong value of |
fmt.Printf(format, arg…) | Use a formatted string format take args write in os.Stdout, Returns the number of bytes written and a value of error perhaps nil The wrong value of |
fmt.Println(format, arg…) | By format %v Separate the parameter with a space and end with a newline character args write in os.Stdout, Returns the number of bytes written and a value of error perhaps nil The wrong value of |
fmt.Sprint(args…) | return args A string composed of parameters , Each parameter uses %v Formatted non string separated by spaces |
fmt.Sprintf(format,args…) | Return to use format format Formatted args character string |
fmt.Sprintln(args) | Return to use format %v format args String after , Separate with spaces and end with newline |
These functions are similar to C in printf and scanf Code in function , as well as Python Old style string formatting in .
Readers who are interested can experience the above functions by themselves .
Split string
string The package only needs to be added into the import block import "strings"
, This package provides us with many string manipulation functions . One of them is a function that splits a string with a delimiter and obtains a string :
package main
import (
"fmt"
"strings"
)
func main() {
myClass := " Xiao Zhang , petty thief , Xiao Wang , Big week "
name := strings.Split(myClass, ",")
fmt.Printf("%q", name) // [" Xiao Zhang " " petty thief " " Xiao Wang " " Big week "]
}
string.Split
Function takes string and separator as parameters .
In this case , We passed " Xiao Zhang , petty thief , Xiao Wang , Big week "
And separator ","
, And receive a string fragment : [" Xiao Zhang " " petty thief " " Xiao Wang " " Big week "]
.
Count and find substrings
Use strings package , We can also calculate the number of non overlapping instances of substrings in a string , The function is strings.Count
.
Take a look at the following code :
package main
import (
"fmt"
"strings"
)
func main() {
test := "January February"
count1 := strings.Count(test, "r")
count2 := strings.Count(test, "uary")
fmt.Println(count1, count2) // 3 2
}
strconv package
strconv Package provides functions to convert strings and other types of data :
strconv.ParseInt(s, base, bits)
: If s Can be converted to an integer , Then return to int64 Values and nil , Otherwise return to 0 and error ; If base by 0 , Then it means to start from s Determine the size of base in .
package main
import (
"fmt"
"strconv"
)
func main() {
// String conversion my number type
fmt.Println("---- demo String To Numeric----")
str1_val1 := "5"
str2_val2 := "2.8769"
var err error
var int_val1 int64
int_val1, err = strconv.ParseInt(str1_val1, 10, 32) // base10, 64 size
if err == nil {
fmt.Println(int_val1)
} else {
fmt.Println(err)
}
var float_val2 float64
float_val2, err = strconv.ParseFloat(str2_val2, 64) // 64 size
if err == nil {
fmt.Println(float_val2)
} else {
fmt.Println(err)
}
// Numeric type to string
fmt.Println("---- demo numeric to string ----")
num1 := 8
num2 := 5.872
var str_num1 string
str_num1 = fmt.Sprintf("%d", num1)
fmt.Println(str_num1)
var str_num2 string
str_num2 = fmt.Sprintf("%f", num2)
fmt.Println(str_num2)
}
Run the above code , The result is :
---- demo String To Numeric----
5
2.8769
---- demo numeric to string ----
8
5.872000