SoFunction
Updated on 2025-03-04

Go language strings and strings and strconv package usage examples

Preface

In Go programming, strings are one of the most basic and commonly used data types. Whether it is processing user input, reading file content, or generating output, string operations are everywhere. In order to facilitate developers to perform various operations on strings, Go provides powerfulstringsBaohestrconvBag.stringsThe package contains a series of functions used to process and manipulate strings, such as search, replacement, segmentation, splicing, etc.strconvThe package focuses on the conversion between strings and other basic data types, making data processing more concise and efficient. In this article, we will explore in-depth string processing methods in Go language and introduce in detailstringsBaohestrconvThe main functions and usage of the package help you better master string operation skills and improve programming efficiency.

1. Character strings in Go language

1.1. GO Language

In Go, strings are sequences of UTF-8 encoded characters. For ASCII characters, each character takes 1 byte, while the other characters take 2 to 4 bytes as needed. UTF-8 is a widely used encoding format that is used in many standard text files such as XML and JSON. Due to the variable length nature of UTF-8 encoding, strings in Go can also take up 1 to 4 bytes, which is different from C++, Java, or Python (for example, Java always uses 2 bytes). This design not only reduces the use of memory and hard disk space, but also eliminates the tedious operation of encoding and decoding UTF-8 text.

A string is a value type in Go and the value is immutable. This means that once a string is created, its contents cannot be modified. To put it more deeply, a string is a fixed-length array of bytes.

1.2. String literal value

Go supports two forms of string literals:

Interpreted Strings:

  • Enclose it in double quotes.
  • Escape characters will be replaced, for example:\nRepresents a newline character,\tRepresents a tab character,\uor\URepresents Unicode characters,\\Indicates the backslash itself.

Example:

var str = "Hello, World!\n"

Non-interpreted strings:

  • Enclose it in backticks.
  • Multi-line strings are supported, escaped characters will not be replaced, and everything will be output as is.

Example:

var rawStr = `This is a raw string \n`

In Go, strings are defined by length, rather than special characters like C/C++\0Finish.stringThe zero value of type is a string of length zero, that is, an empty string""

1.3. String comparison and operation

Strings can be passed through common comparison operators (==!=<<=>=>) Compare in memory by bytes. Can be usedlen()Functions get the byte length of a string:

len("hello") // 5

The contents of the string (bytes) can be accessed through an index, which starts with 0:

var str = "hello"
str[0] // 'h'
str[len(str)-1] // 'o'

It should be noted that this indexing method is only valid for pure ASCII strings. For Unicode characters, you need to useunicode/utf8Methods provided by the package.

1.4. String stitching

Strings can be used+Operator stitching:

var s1 = "hello"
var s2 = "world"
var s = s1 + " " + s2 // "hello world"

Can also be used+=Operators are spliced:

var s = "hello"
s += ", "
s += "world!" // "hello, world!"

Use in a loop+String splicing is not the most efficient method. A better way is to use()Function, or usePerform efficient string stitching.

1.5. Other operations of strings

In Go, strings can be treated as bytes (byte) slices (slice), thereby implementing standard indexing operations. useforLoops can return bytes in a string based on the index. and usefor-rangeLoops can iterate on Unicode strings.

In addition, Go provides a rich variety of string operation functions and methods, which can be found in the standard library.stringsandunicode/utf8Found in the package. For example, you can use(x)To format the generation and return the string.

1.6. Example: Statistics bytes and characters

Create a program to count the number of bytes and characters in a string. For example, analyze strings"asSASA ddd dsjkdsjs dk"and"asSASA ddd dsjkdsjsこん dk"and explain the reasons for the difference between the two (tip: Useunicode/utf8Bag).

Sample code:

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	str1 := "asSASA ddd dsjkdsjs dk"
	str2 := "asSASA ddd dsjkdsjsこん dk"

	("String: %s\n", str1)
	("Bytes: %d, Runes: %d\n", len(str1), (str1))

	("String: %s\n", str2)
	("Bytes: %d, Runes: %d\n", len(str2), (str2))
}

The program counts and outputs the bytes and rune numbers of strings, thus demonstrating the differences in UTF-8 encoding when processing different characters.

2. strings and strconv packages

In Go, strings are a basic data structure and have many predefined processing functions.stringsThe package is used to perform main operations on strings, andstrconvPackages are used to convert between strings and other types.

2.1. strings package

stringsThe package provides a rich string operation function, and the following are some common operations:

2.1.1. Prefixes and suffixes

  • (s, prefix string) bool:Judge stringsWhether toprefixThe beginning.
  • (s, suffix string) bool:Judge stringsWhether tosuffixEnd.

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "This is an example of a string"
	("T/F? Does the string \"%s\" have prefix %s? ", str, "Th")
	("%t\n", (str, "Th"))
}

Output:

T/F? Does the string "This is an example of a string" have prefix Th? true

2.1.2. String inclusion relationship

  • (s, substr string) bool:Judge stringsWhether substrings are includedsubstr

2.1.3. Determine the location where a child string or character appears in the parent string (index)

  • (s, str string) int: Return substringstrIn stringsThe index of the first occurrence position in  , -1 means that it is not included.
  • (s, str string) int: Return substringstrIn stringsThe index of the last occurrence position in  , -1 means that it is not included.
  • (s string, r rune) int: Return charactersrIn stringsindex in  .

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hi, I'm Marc, Hi."

	("The position of \"Marc\" is: %d\n", (str, "Marc"))
	("The position of the first instance of \"Hi\" is: %d\n", (str, "Hi"))
	("The position of the last instance of \"Hi\" is: %d\n", (str, "Hi"))
	("The position of \"Burger\" is: %d\n", (str, "Burger"))
}

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

2.1.4. String replacement

  • (str, old, new string, n int) string: Put the stringstrThe front of thenA stringoldReplace with stringnewand return a new string. ifn = -1, then replace all stringsold

2.1.5. Statistics the number of occurrences of strings

  • (s, str string) int: Calculate stringstrIn stringsThe number of non-overlapping times that appear in  .

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Hello, how is it going, Hugo?"
	manyG := "gggggggggg"

	("Number of H's in %s is: %d\n", str, (str, "H"))
	("Number of double g's in %s is: %d\n", manyG, (manyG, "gg"))
}

Output:

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

2.1.6. Repeat strings

  • (s, count int) string: Returns a new string, which is bycountRepeat stringsComposition.

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	origS := "Hi there! "
	newS := (origS, 3)
	("The new repeated string is: %s\n", newS)
}

Output:

The new repeated string is: Hi there! Hi there! Hi there!

2.1.7. Modify the upper and lower case of strings

  • (s) string: Put the stringsAll Unicode characters in  convert to lowercase.
  • (s) string: Put the stringsAll Unicode characters in  convert to uppercase.

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	orig := "Hey, how are you George?"
	("The original string is: %s\n", orig)
	("The lowercase string is: %s\n", (orig))
	("The uppercase string is: %s\n", (orig))
}

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?

2.1.8. Trim strings

  • (s): Remove blank symbols at the beginning and end of a string.
  • (s, cutset): Exclude specified characters at the beginning and end of a stringcutset
  • (s, cutset): Remove the specified characters at the beginning of the stringcutset
  • (s, cutset): Remove the specified characters at the end of the stringcutset

2.1.9. Splitting strings

  • (s): Split the string according to the whitespace character and return a string slice.
  • (s, sep): According to the specified separatorsepSplit the string and return a string slice.

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "The quick brown fox jumps over the lazy dog"
	sl := (str)
	("Splitted in slice: %v\n", sl)
	for _, val := range sl {
		("%s - ", val)
	}
	()

	str2 := "GO1|The ABC of Go|25"
	sl2 := (str2, "|")
	("Splitted in slice: %v\n", sl2)
	for _, val := range sl2 {
		("%s - ", val)
	}
	()

	str3 := (sl2, ";")
	("sl2 joined by ;: %s\n", str3)
}

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

2.1.10. Splice slice to string

  • (sl []string, sep string) string: Type the element asstringThe slice uses the splittersepSpliced ​​into a string.

2.1.11. Read content from a string

  • (str): Generate a Reader and read the contents of the string, and return a pointer to the Reader.

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "The quick brown fox jumps over the lazy dog"
	sl := (str)
	("Splitted in slice: %v\n", sl)
	for _, val := range sl {
		("%s - ", val)
	}
	()
	str2 := "GO1|The ABC of Go|25"
	sl2 := (str2, "|")
	("Splitted in slice: %v\n", sl2)
	for _, val := range sl2 {
		("%s - ", val)
	}
	()
	str3 := (sl2,";")
	("sl2 joined by ;: %s\n", str3)
}

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

For more string operations documentation, please refer to the official documentation.

2.2. strconv package

strconvPackages are used to convert between strings and other basic data types.

2.2.1. Convert other types to strings

  • (i int) string: Convert integers to strings.
  • (f float64, fmt byte, prec int, bitSize int) string: Convert floating point numbers to strings,fmtDenote format,precDenotes accuracy,bitSizeUsed to distinguishfloat32andfloat64

Example:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var i int =

 123
	var f float64 = 3.14159

	s1 := (i)
	s2 := (f, 'f', -1, 64)

	("Integer to string: %s\n", s1)
	("Float to string: %s\n", s2)
}

Output:

Integer to string: 123
Float to string: 3.14159

2.2.2. Convert string to other types

  • (s string) (int, error): Convert a string to an integer.
  • (s string, bitSize int) (float64, error): Convert a string to a floating point number.

Example:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var str string = "666"
	var anInt int
	var newStr string

	anInt, _ = (str)
	("The integer is: %d\n", anInt)

	anInt += 5
	newStr = (anInt)
	("The new string is: %s\n", newStr)
}

Output:

The integer is: 666
The new string is: 671

strconvThe package also contains some auxiliary variables, such as, used to obtain the current platformintThe size of the type (digit number).

passstringsandstrconvThe powerful functions of the package, Go language provides a rich variety of string processing and conversion tools, allowing developers to efficiently process and convert string data.

Attachment: Which decimal point in the numeric string is read in Go language

In Go, you can use the ParseFloat function in the strconv package to convert a string to a number and read which bit of the decimal point in the string. The specific usage methods are as follows:

import "strconv"

str := "123.456789"
num, _ := (str, 64) //  Set [string](/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4L  CJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&amp;spm=1055.2569.3001.10083) Convert to  float64 type numberdotIndex := ((num, 'f', -1, 64), ".") //  Read the decimal point in [string](/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM  4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&amp;spm=1055.2569.3001.10083)
(dotIndex) // Output is 3

In the ParseFloat function, the first parameter indicates the number that needs to be converted toString, the second parameter indicates the conversion using the float64 type. In the example above, after we convert the string to a number, we use the FormatFloat function to read the position of the decimal point in the string. In the FormatFloat function, 'f' means formatted as a floating point number, -1 means unlimited decimal places, and 64 means formatting using a float64 type number. Then use the Index function in the strings package to read the position of the decimal point in the string.

Summarize

This is the article about Go strings and the use of strings and strconv packages. For more related Go strings and strconv packages, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!