SoFunction
Updated on 2025-03-05

Go language string operation guide: easy to understand practical skills

In this article, we explore the charm and depth of strings in Go. From basic definitions, operations, character encoding to complex type conversions, each link comes with instances and code examples to deepen your understanding. Through these in-depth analysis, readers can not only master the core concepts of strings in Go, but also gain insight into the thoughts behind Go design philosophy.

1. Introduction

In modern programming, string processing is an indispensable part. Whether it is a simple user interface or complex data processing, strings play a key role. Go, as a modern and highly performant programming language, provides a series of powerful tools and functions for string processing.

Article structure overview

To help readers understand strings in Go, we will discuss the following topics in the article:

  • Basic definitions and characteristics of Go strings.
  • How to perform common string operations in Go.
  • Character encoding, especially the application of UTF-8 in Go.
  • How to convert various types of strings.

Through the in-depth analysis of this article, you can have a comprehensive and in-depth understanding of Go strings and be able to be handy in practical applications.

2. Go string basics

Strings are crucial in the programming world, and whether you are processing user input or reading data from a database, strings are inseparable from them. Go provides a simple and efficient tool for string processing.

Definition and characteristics of strings

What is a string?

Definition: In Go, a string is a collection of arbitrary bytes, usually used to represent text. A string is immutable, which means you cannot modify a certain character of the string, but you can generate a new string.

example:

// Define a stringgreeting := "Hello, Go!"
(greeting) ?// Output: Hello, Go!

The principle of immutability of Go strings

Definition: Every string created in Go is immutable. This means you cannot modify characters in the string directly. This design can bring some performance benefits to string manipulation, especially when string copying and passing.

example:

str := "GoLang"
// str[0] = 'g' ?// This will report an errornewStr := "g" + str[1:]
(newStr) ?// Output: golang, By creating a new string"Revise"Original string

Data structure of strings

The internal expression of Go strings

Definition: Behind the Go string is a byte array, which also means that Go is able to store any data, not just UTF-8 text.

example:

// String and its corresponding bytesstr := "Hello"
for i := 0; i < len(str); i++ {
? ? ("%x ", str[i]) ?// Output a hexadecimal representation of each character}
// Output: 48 65 6c 6c 6f

Introduction to byte and rune

definition:

byte is an alias for uint8 and is usually used to handle ASCII characters.
rune is an alias for int32, used to process a UTF-8 character or Unicode code point.

example:

// byte and ASCII charactersbyteValue := byte('A')
(byteValue) ?// Output: 65// Rune and UTF-8 charactersruneValue := rune('you')
("%#U \n", runeValue) ?// Output: U+4F60

3. String operations and applications

Handling strings is part of daily programming tasks, Go provides a complete set of tools and standard library functions to make these operations simple and efficient.

3.1 Operation and Application

String connection
Definition: In Go, two or more strings can be concatenated using the + operator.

example:

// String connectionstr1 := "Hello"
str2 := "World"
result := str1 + ", " + str2
(result) ?// Output: Hello, World

String slices
Definition: Since there is a byte slice behind the Go string, you can process the string like you would do with an array or slice, getting a substring of the string.

example:

// String slicestr := "GoLang"
subStr := str[2:4]
(subStr) ?// Output: La

String search

Definition: Use functions in the strings package, such as Contains, Index, etc., to easily find substrings or characters.

example:

import "strings"

str := "Hello, Go!"
found := (str, "Go")
(found) ?// Output: true
position := (str, "Go")
(position) ?// Output: 7

String comparison
Definition: Go provides a native way to compare two strings equal. In addition, the Compare function in the strings library can be used to determine the sequence of two strings in dictionary order.

example:

str1 := "apple"
str2 := "banana"

// Use == to compare stringsisEqual := str1 == str2
(isEqual) ?// Output: false
// Use comparison stringcompResult := (str1, str2)
(compResult) ?// Output: -1, expressstr1existstr2Before

String replacement
Definition: Using the Replace and ReplaceAll functions in the strings package, you can replace substrings in strings.

example:

source := "go is good, go is great"
replaced := (source, "go", "Go")
(replaced) ?// Output: Go is good, Go is great

Case conversion of strings
Definition: The strings library provides ToUpper and ToLower functions for case conversion.

example:

str := "GoLang"
lowercase := (str)
uppercase := (str)
(lowercase) ?// Output: golang(uppercase) ?// Output: GOLANG

Handling strings using regular expressions
Definition: Go's regexp library provides a series of functions to use regular expressions to query, match, replace and split strings.

example:

import "regexp"

str := "My email is example@"
re := (`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}`)
email := (str)
(email) ?// Output: example@

Encryption and hashing of strings
Definition: Go's crypto package provides a variety of encryption algorithms that you can use to encrypt strings or calculate the hash of strings.

example:

import (
? ? "crypto/md5"
? ? "fmt"
? ? "io"
)
str := "secret data"
hasher := ()
(hasher, str)
("%x\n", (nil)) ?// Output: md5Hash value

String splitting
Definition: Using functions, you can split a string into a slice of a substring by the specified delimiter.

example:

str := "apple,banana,cherry"
items := (str, ",")
(items) ?// Output: [apple banana cherry]

String merge
Definition: Functions are able to merge a string slice into a separate string.

example:

items := []string{"apple", "banana", "cherry"}
str := (items, ", ")
(str) ?// Output: apple, banana, cherry

Get characters in a string
Definition: Each character in a string can be accessed through an index, but the character's byte value is returned.

example:

str := "Go"
byteValue := str[1]
(byteValue) ?// Output: 111 (ASCIICoded'o')

Traversal of characters in strings
Definition: Use a for range loop to iterate over each character in a string.

example:

str := "Go"
for index, char := range str {
? ? ("At index %d, char: %c\n", index, char)
}

Trim strings
Definition: Functions can remove spaces at the beginning and end of a string.

example:

str := " ? Go Lang ? "
trimmed := (str)
(trimmed) ?// Output: Go Lang

Fill string
Definition: Using the fmt package, you can use specific format modifiers to fill or align strings.

example:

str := "Go"
padded := ("%-10s", str)
(padded) ?// Output: Go ? ? ? ?

Statistics of strings
Definition: Functions can help count the number of times a substring appears in a string.

example:

str := "Go is easy to learn. Go is powerful."
count := (str, "Go")
(count) ?// Output: 2

3.2 Using the standard library to process strings

Overview of strings library
Definition: The strings library provides a series of powerful functions for string query, substitution, conversion, and slicing operations.

example:

import "strings"
str := "go is awesome"
title := (str)
(title) ?// Output: Go Is Awesome

Other useful string libraries

strconv library: used to convert between strings and other basic data types.

example:

import "strconv"
number := 12345
strNum := (number)
(strNum) ?// Output: "12345"

unicode library: used to check character attributes, such as whether they are numbers, letters, etc.

example:

import "unicode"
ch := 'A'
isLetter := (ch)
(isLetter) ?// Output: true

4. Go string character encoding

Character strings are stored and represented in computers by character encoding. In Go, strings are encoded by default with UTF-8, meaning it can easily represent any Unicode character.

What is character encoding?
Definition: Character encoding is a set of rules used to convert characters into digital codes that can be understood by computers. Common character encodings include ASCII, ISO-8859-1 and UTF-8.

Introduction to UTF-8 Coding
Definition: UTF-8 is a variable-length Unicode character encoding method, using 1 to 4 bytes to represent a character. It is the official recommended code for Unicode standards.

example:

str := "Go"
for i := 0; i < len(str); i++ {
? ? ("%x ", str[i])
}
// Output: 47 6f?

Unicode code points and rune types
Definition: Unicode code points are unique numerical representations of each character. In Go, the rune type can be used to store and process Unicode code points.

example:

str := "language"
for _, char := range str {
? ? ("U+%04X ", char)
}
// Output: U+8BED U+8A00

String interoperate with UTF-8
Get the string length
Definition: Use the len function to get the byte length of a string, but under UTF-8 encoding, you need to use to get the number of characters.

example:

str := "language"
byteLen := len(str)
runeLen := (str)
(byteLen) ?// Output: 6(runeLen) ?// Output: 2

Decode the string into a rune slice
Definition: Use []rune to convert a string to a rune slice.

example:

str := "language"
runes := []rune(str)
(runes) ?// Output: [35821 35328]

Convert character encoding
Although Go mainly supports UTF-8, it may sometimes require interoperability with other character encodings, such as ISO-8859-1 or GBK. At this time, you can use third-party libraries, such as /x/text/encoding.

example:

// Please install /x/text/encoding firstimport "/x/text/encoding/simplifiedchinese"
import "/x/text/transform"
str := "language"
encoder := simplifiedchinese.()
encoded, _, _ := (encoder, str)
(encoded) ?// Output: GBKEncoded string

5. Go string type conversion

In Go, string-related type conversion is very common. This involves converting other basic data types (such as integers, floating-point numbers) to strings, or vice versa. These common conversion methods are discussed in the following sections.

Strings and integers

Integer to string
Definition: Use functions to convert integers into strings.

example:

num := 123
str := (num)
(str) ?// Output: "123"

String to integer
Definition: Functions can convert strings into integers.

example:

str := "456"
num, err := (str)
if err != nil {
? ? (err)
} else {
? ? (num) ?// Output: 456}

String and floating point numbers

Floating point number to string
Definition: Using functions, you can convert floating point numbers to strings.

example:

f := 3.14
str := (f, 'f', 2, 64)
(str) ?// Output: "3.14"

String to floating point number
Definition: Functions can convert strings to floating point numbers.

example:

str := "5.67"
f, err := (str, 64)
if err != nil {
? ? (err)
} else {
? ? (f) ?// Output: 5.67}

String and byte slices

String to byte slice

Definition: Use type conversion to convert a string to a byte slice.

example:

str := "Go"
bytes := []byte(str)
(bytes) ?// Output: [71 111]

Byte slice to string

Definition: Using type conversion, you can convert byte slices into strings.

example:

bytes := []byte{72, 101, 108, 108, 111}
str := string(bytes)
(str) ?// Output: "Hello"

6. Summary

Strings are a basic and indispensable data type in programming. Through this article, we have a deeper understanding of the internal working mechanism, operations, character encoding of strings in Go language, and how to perform various types of conversions. These knowledge points not only demonstrate the power of Go for string manipulation, but also reveal how it handles multilingual text gracefully.

From Go's design philosophy, we can see how it balances performance, security, and ease of use. The string is read-only, which makes it safe in concurrency. At the same time, Go uses UTF-8 as its default encoding, making global application development simple and intuitive.

This is the article about Go string operation guide: simple and easy-to-understand practical skills. For more relevant Go string operation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!