SoFunction
Updated on 2025-03-03

Basic usage example code of strings package in Go

This article mainly summarizes the operation explanation of some functions of the string package in go

string

In each language, there are corresponding packages for processing strings, which are processed using strings in go

Prefixes and suffixes

HasPrefix() determines whether the string s starts with prefix:

(s, prefix string) bool

HasSuffix() determines whether the string s ends with sffix:

(s, suffix string) bool

Sample code

func test1() {
	(("this is string", "this"))
	(("this is string", "1this"))
	(("this is string", "ing"))
	(("this is string", "iing"))
}

String contains

Contains() determines whether the string s contains substr:

(s, substr string) bool

Sample code

func test2() {
	totalString := "hello go, i love cpp"
	containString1 := "go"
	containString2 := "cpp"
	containString3 := "java"
	("\"%s\" contain in \"%s\"? the ans is %t\n", containString1, totalString, (totalString, containString1))
	("\"%s\" contain in \"%s\"? the ans is %t\n", containString2, totalString, (totalString, containString2))
	("\"%s\" contain in \"%s\"? the ans is %t\n", containString3, totalString, (totalString, containString3))
}

Here we review the use of escaped characters in Go

Determine where a child string or character appears in the parent string

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

(s, str string) int

LastIndex() returns the index of the last occurrence position of the string str in the string s (the index of the first character of str). -1 means that the string s does not contain the string str:

(s, str string) int

Sample code:

func test3() {
	totalString := "hello go, i love cpp, i love cpp and go"
	containString1 := "go"
	containString2 := "cpp"
	containString3 := "java"
	("first index demo is:")
	("\"%s\" first index in \"%s\" is %d\n", containString1, totalString, (totalString, containString1))
	("\"%s\" first index in \"%s\" is %d\n", containString2, totalString, (totalString, containString2))
	("\"%s\" first index in \"%s\" is %d\n", containString3, totalString, (totalString, containString3))
	("last index demo is:")
	("\"%s\" first index in \"%s\" is %d\n", containString1, totalString, (totalString, containString1))
	("\"%s\" first index in \"%s\" is %d\n", containString2, totalString, (totalString, containString2))
	("\"%s\" first index in \"%s\" is %d\n", containString3, totalString, (totalString, containString3))
}

The running result is:

first index demo is:
"go" first index in "hello go, i love cpp, i love cpp and go" is 6
"cpp" first index in "hello go, i love cpp, i love cpp and go" is 17
"java" first index in "hello go, i love cpp, i love cpp and go" is -1
last index demo is:
"go" first index in "hello go, i love cpp, i love cpp and go" is 37
"cpp" first index in "hello go, i love cpp, i love cpp and go" is 29
"java" first index in "hello go, i love cpp, i love cpp and go" is -1

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

(s string, r rune) int

String replacement

Replace() is used to replace the first n strings old in the string str with the string new and return a new string. If n = -1, replace all strings old as string new:

(str, old, new string, n int) string

Sample code

func test4() {
	str1 := "hello hello hello hello hello hello"
	str2 := (str1, "hello", "no", -1)
	(str2)
}

The meaning of this function is that as long as there is a substitutable string, and for the last number, it does not exceed the limit, the moral recognition string will be replaced with the string you want to replace. For example, in this example, when the string contains Hello, this word will replace hello with no, provided that there is no limit exceeding -1. Because -1 means that as long as there is a string, it will replace all the strings containing hello in this string with no

Statistics the number of occurrences of strings

Count() is used to calculate the number of non-overlapping times a string str appears in the string s:

(s, str string) int

Sample code

func test5() {
	str1 := "hello world hello world hellhello world"
	((str1, "hello"))
	((str1, "world"))
}

Repeat string

Repeat() is used to repeat count string s and return a new string:

(s, count int) string

Sample code

func test6() {
	str := "hello go"
	((str, 10))
	((str, 2))
}

Modify the upper and lowercase strings

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

(s) string

ToUpper() converts all Unicode characters in the string to corresponding capital characters:

(s) string

Sample code

func test7() {
	str := "hello World This is TEST"
	((str))
	((str))
}

Trim strings

You can use (s) to remove blank symbols at the beginning and end of a string; if you want to remove specified characters, you can use (s, "cut") to remove cuts at the beginning and end. The second argument of the function can contain any character, if you only want to remove the string at the beginning or end, you can use TrimLeft() or TrimRight() to implement it.

Sample code

func test8() {
	str1 := "11hello world111"
	str2 := "  hello go    "
	("Remove blanks")
	((str1))
	((str2))
	("Remove the left blank")
	((str2, " "))
	("Remove left character 1")
	((str1, "1"))
	("Remove the right character 1")
	((str1, "1"))
	("Remove left and right sides 1")
	((str1, "1"))
}

Split string

(s) will use 1 or more whitespace symbols as dynamic-length separators to split the string into small pieces and return a slice. If the string only contains whitespace symbols, it will return a slice of length 0.

(s, sep) is used to customize the segmentation symbol to segment the specified string, and also returns slice.

Because these 2 functions will return slices, it is accustomed to using for-range loops to process them

Sample code

func test9() {
	str1 := "hello1 hello2 hello3      hello4"
	("Taking a space as the separator")
	s1 := (str1, " ")
	for _, t := range s1 {
		(t)
	}
	("Taking one or more spaces as separators")
	s2 := (str1)
	for _, t := range s2 {
		(t)
	}
	str3 := "hello11hello22hello321321312hello4"
	("Use hello as the separator")
	s3 := (str3, "hello")
	for _, t := range s3 {
		(t)
	}
}

Splice slice to string

Join() is used to splice slices with element type string to form a string using split symbols:

(sl []string, sep string) string

Sample code

func test10() {
	// Define a string slice	sl := []string{"apple", "banana", "cherry"}
	// Use spaces as separators to splice strings in slices	result := (sl, " ")
	(result) // Output "apple banana cherry"	// Use commas and spaces as separators to splice strings in slices	result2 := (sl, ", ")
	(result2) // Output "apple, banana, cherry"}

strconv

Converting data of string type and other types of data is actually done with the help of this package

Here we will only talk about the most basic content, and then explain the other contents later.

Sample code:

func test11() {
	str1 := "666"
	number, _ := (str1)
	(number)
	((number + 5))
}

This is the article about the basic use of Go: strings package. For more related content on using Go strings package, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!