Commonly used string processing functions in Go | Go Topic Month

Commonly used string processing functions in Go | Go Topic Month

The functions for processing strings in the go language are mainly in the two packages strings and strconv.

strings and strconv packages

As a basic data structure, each language has some predefined processing functions for strings. Use in Go

strings
Package to complete the main operations on the string.

Prefix and suffix

HasPrefix
Judgment string
s
Whether to
prefix
beginning:

strings.HasPrefix (S, prefix String ) BOOL duplicated code

HasSuffix
Judgment string
s
Whether to
suffix
end:

strings.HasSuffix (S, suffix String ) BOOL duplicated code

Example

package main import ( "fmt" "strings" ) func main () { 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 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 escape character

\
And the use of formatting strings.

String containment relationship

Contains
Judgment string
s
Does it contain
substr
:

strings.Contains (S, substr String ) BOOL duplicated code

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

Index
Return string
str
In the string
s
Index in (
str
Index of the first character), -1 means string
s
Does not contain string
str
:

strings.Index (S, STR String ) int duplicated code

LastIndex
Return string
str
In the string
s
The index of the last occurrence in (
str
Index of the first character), -1 means string
s
Does not contain string
str
:

strings.LastIndex (S, STR String ) int duplicated code

If you need to query the position of a non-ASCII encoded character in the parent string, it is recommended to use the following function to locate the character:

strings.IndexRune (S String , R & lt Rune ) int duplicated code
Note: The original text is "If ch is a non-ASCII character use strings.IndexRune(s string, ch int) int." This method is defined as func IndexRune(s string, r rune) int in the latest version of Go The second parameter rune in actual use can be rune or int, such as strings.IndexRune("chicken", 99) or strings.IndexRune("chicken", rune('k')) Copy code

Example

package main import ( "fmt" "strings" ) func main () { 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 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 code

String replacement

Replace
Used to string
str
In the front
n
Strings
old
Replace with string
new
And returns a new string if
n = -1
Replace all strings
old
As a string
new
:

strings.Replace (STR, Old, new new , n-) String duplicated code

Count the number of occurrences of a string

Count
Used to calculate strings
str
In the string
s
Number of non-overlapping occurrences in:

strings.Count (S, STR String ) int duplicated code

Example

package main import ( "fmt" "strings" ) func main () { 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 code

Output:

Number of H's in Hello, how is it going, Hugo? is: 2 Number of double g's in gggggggggg is: 5 Copy code

Repeated string

Repeat
For repetition
count
Substring
s
And return a new string:

strings.Repeat (S, COUNT int ) String duplicated code

Example

package main import ( "fmt" "strings" ) func main () { var origS string = "Hi there! " var newS string newS = strings.Repeat(origS, 3 ) fmt.Printf( "The new repeated string is: %s\n" , newS) } Copy code

Output:

The new repeated string is:! Hi there Hi there Hi there!! Copy the code

Modify string case

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

strings.ToLower (S) String duplicated code

ToUpper
Convert all Unicode characters in the string to corresponding uppercase characters:

strings.ToUpper (S) String duplicated code

Example

package main import ( "fmt" "strings" ) func main () { 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 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 code

Trim string

you can use

strings.TrimSpace(s)
To remove the white space at the beginning and end of the string; if you want to remove the specified characters, you can use
strings.Trim(s, "cut")
To change the beginning and end
cut
Remove. The second parameter of the function can contain any characters, if you only want to exclude the beginning or end of the string, you can use
TrimLeft
or
TrimRight
to realise.

Split string

strings.Fields(s)
One or more blank characters will be used as dynamic-length separators to divide the string into several small pieces and return a slice. If the string contains only blank characters, a slice with a length of 0 will be returned.

strings.Split(s, sep)
Used to customize the splitting symbol to split the specified string, and also return slice.

Because these two functions both return slices, I am used to using a for-range loop to process them (Section 7.3).

Concatenate slices to strings

Join
Used to concatenate slices whose element type is string to form a string using segmentation symbols:

strings.Join (SL [] String , On Sep String ) String duplicated code

Example

package main import ( "fmt" "strings" ) func main () { 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 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;25 Copy code

Other documents related to the string operations, see the official documentation ( Translator's Note: domestic users can access the page ).

Read content from string

function

strings.NewReader(str)
Used to generate a
Reader
And read the contents of the string, and then return to point to the
Reader
Pointers, functions to read content from other types include:

  • Read()
    Read the content from []byte.
  • ReadByte()
    with
    ReadRune()
    Read the next byte or rune from the string.

String and other types of conversion

Type conversions related to strings are all through

strconv
The package is implemented.

This package contains some variables used to obtain the number of bits occupied by the int type under the operating system platform the program is running on, such as:

strconv.IntSize
.

Any type T converted to a string is always successful.

For converting from a number type to a string, Go provides the following functions:

  • strconv.Itoa(i int) string
    Returns the decimal number of the string type represented by the number i.
  • strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) string
    Convert a 64-bit floating point number to a string, where
    fmt
    Represents the format (its value can be
    'b'
    ,
    'e'
    ,
    'f'
    or
    'g'
    ),
    prec
    Represents accuracy,
    bitSize
    Then use 32 for float32 and 64 for float64.

Converting strings to other types of tp is not always possible and may throw errors at runtime

parsing " ": invalid argument
.

For converting from string type to number type, Go provides the following functions:

  • strconv.Atoi(s string) (i int, err error)
    Convert a string to int type.
  • strconv.ParseFloat(s string, bitSize int) (f float64, err error)
    Convert the string to float64 type.

Using the feature of multiple return values, these functions will return 2 values, the first is the result of the conversion (if the conversion is successful), and the second is a possible error. Therefore, we generally use the following form to perform the conversion from the string Conversion to other types:

val, err = strconv.Atoi (s) copying the code

In the following example, we ignore possible conversion errors:

Example

package main import ( "fmt" "strconv" ) func main () { 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 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: 671 Copy code