去程式設計 |字串基礎知識 |字元編碼
介紹
在上一課中,我們了解到 Go 中的字元使用 UTF-8 進行編碼並儲存為 byte 或 rune 類型。現在,我們來談談字串,它是字元的集合。一起來了解一下吧。
知識點:
- 什麼是字串
- 建立字串
- 宣告一個字串
- 常用字串函數
什麼是字串
在我們用 Go 學習的第一個程式中,我們列印了字串 hello, world。
String 是 Go 中的一種基本資料類型,也稱為字串文字。可以理解為字元的集合,佔用一塊連續的記憶體區塊。這塊記憶體可以儲存任何類型的數據,例如字母、文字、表情符號等
但是,與其他語言不同,Go 中的字串是唯讀的,無法修改。
建立字串
字串可以透過多種方式宣告。讓我們來看看第一種方法。建立一個名為 string.go 的新檔案:
touch ~/project/string.go
編寫以下程式碼:
package main import "fmt" func main() { // Use the var keyword to create a string variable a var a string = "labex" a = "labex" // Assign "labex" to variable a // Declare variable a and assign its value var b string = "shiyanlou" // Type declaration can be omitted var c = "Monday" // Use := for quick declaration and assignment d := "Hangzhou" fmt.Println(a, b, c, d) }
上面的程式碼示範如何使用 var 關鍵字和 := 運算子建立字串。如果用var建立變數時賦值,可以省略型別聲明,如建立變數b所示。
預期輸出如下:
labex shiyanlou Monday Hangzhou
聲明一個字串
大多數情況下,我們使用雙引號「」來宣告字串。雙引號的優點是可以用作轉義序列。例如,在下面的程式中,我們使用 n 轉義序列來建立新行:
package main import "fmt" func main(){ x := "shiyanlou\nlabex" fmt.Println(x) }
預期輸出如下:
shiyanlou labex
以下是一些常見的轉義序列:
Symbol | Description |
---|---|
n | New line |
r | Carriage return |
t | Tab |
b | Backspace |
\ | Backslash |
' | Single quote |
" | Double quote |
If you want to preserve the original format of the text or need to use multiple lines, you can use backticks to represent them:
package main import "fmt" func main() { // Output Pascal's Triangle yangHuiTriangle := ` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1` fmt.Println(yangHuiTriangle) // Output the ASCII art of "labex" ascii := ` # ## # # ### # ## #### # # # ## # # # # # # # # # # # # # # # # # # # # # # ##### # # # # # # # ##### # # # # # # ## # # # # # # # ##### # # # # ## # # # # ### ` fmt.Println(ascii) }
After running the program, you will see the following output:
Backticks are commonly used in prompts, HTML templates, and other cases where you need to preserve the original format of the output.
Getting the Length of a String
In the previous lesson, we learned that English characters and general punctuation marks occupy one byte, while Chinese characters occupy three to four bytes.
Therefore, in Go, we can use the len() function to get the byte length of a string. If there are no characters that occupy multiple bytes, the len() function can be used to approximately measure the length of the string.
If a string contains characters that occupy multiple bytes, you can use the utf8.RuneCountInString function to get the actual number of characters in the string.
Let's see an example. Write the following code to the string.go file:
package main import ( "fmt" "unicode/utf8" ) func main() { // Declare two empty strings using var and := var a string b := "" c := "labex" // Output byte length fmt.Printf("The value of a is %s, the byte length of a is: %d\n", a, len(a)) fmt.Printf("The value of b is %s, the byte length of b is: %d\n", b, len(b)) fmt.Printf("The value of c is %s, the byte length of c is: %d\n", c, len(c)) // Output string length fmt.Printf("The length of d is: %d\n", utf8.RuneCountInString(d)) }
The expected output is as follows:
The value of a is , the byte length of a is: 0 The value of b is , the byte length of b is: 0 The value of c is labex, the byte length of c is: 5 The length of d is: 9
In the program, we first declared two empty strings and the string labex. You can see that their byte lengths and actual lengths are the same.
Converting Strings and Integers
We can use functions from the strconv package to convert between strings and integers:
package main import ( "fmt" "strconv" ) func main() { // Declare a string a and an integer b a, b := "233", 223 // Use Atoi to convert an integer to a string c, _ := strconv.Atoi(a) // Use Sprintf and Itoa functions respectively // to convert a string to an integer d1 := fmt.Sprintf("%d", b) d2 := strconv.Itoa(b) fmt.Printf("The type of a: %T\n", a) // string fmt.Printf("The type of b: %T\n", b) // int fmt.Printf("The type of c: %T\n", c) // int fmt.Printf("The type of d1: %T\n", d1) // string fmt.Printf("The type of d2: %T\n", d2) // string }
The expected output is as follows:
The type of a: string The type of b: int The type of c: int The type of d1: string The type of d2: string
In the program, we use the Sprintf() function from the fmt package, which has the following format:
func Sprintf(format string, a ...interface{}) string
format is a string with escape sequences, a is a constant or variable that provides values for the escape sequences, and ... means that there can be multiple variables of the same type as a. The string after the function represents that Sprintf returns a string. Here's an example of using this function:
a = Sprintf("%d+%d=%d", 1, 2, 3) fmt.Println(a) // 1+2=3
In this code snippet, the format is passed with three integer variables 1, 2, and 3. The %d integer escape character in format is replaced by the integer values, and the Sprintf function returns the result after replacement, 1+2=3.
Also, note that when using strconv.Atoi() to convert an integer to a string, the function returns two values, the converted integer val and the error code err. Because in Go, if you declare a variable, you must use it, we can use an underscore _ to comment out the err variable.
When strconv.Atoi() converts correctly, err returns nil. When an error occurs during conversion, err returns the error message, and the value of val will be 0. You can change the value of string a and replace the underscore with a normal variable to try it yourself.
Concatenating Strings
The simplest way to concatenate two or more strings is to use the + symbol. We can also use the fmt.Sprintf() function to concatenate strings. Let's take a look at an example:
package main import ( "fmt" ) func main() { a, b := "lan", "qiao" // Concatenate using the simplest method, + c1 := a + b // Concatenate using the Sprintf function c2 := fmt.Sprintf("%s%s", a, b) fmt.Println(a, b, c1, c2) // lan qiao labex labex }
The expected output is as follows:
lan qiao labex labex
In the program, we also used the Sprintf() function from the fmt package to concatenate strings and print the results.
Removing Leading and Trailing Spaces from a String
We can use the strings.TrimSpace function to remove leading and trailing spaces from a string. The function takes a string as input and returns the string with leading and trailing spaces removed. The format is as follows:
func TrimSpace(s string) string
Here is an example:
package main import ( "fmt" "strings" ) func main() { a := " \t \n labex \n \t hangzhou" fmt.Println(strings.TrimSpace(a)) }
The expected output is as follows:
labex hangzhou
Summary
To summarize what we've learned in this lesson:
- The relationship between strings and characters
- Two ways to declare strings
- Concatenating strings
- Removing leading and trailing spaces from a string
In this lesson, we explained the strings we use in daily life. We've learned about the relationship between strings and characters, mastered string creation and declaration, and gained some knowledge of common string functions.
In the next lesson, we will learn about constants.
? Practice Now: Go String Fundamentals
Want to Learn More?
- ? Learn the latest Go Skill Trees
- ? Read More Go Tutorials
- ? Join our Discord or tweet us @WeAreLabEx
以上是去程式設計 |字串基礎知識 |字元編碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Go 語言的接口雖然不強制類型顯式聲明實現,但它們在實現多態和代碼解耦方面仍然至關重要。通過定義一組方法簽名,接口允許不同的類型以統一的方式進行處理,從而實現靈活的代碼設計和可擴展性。本文將深入探討 Go 接口的特性,並通過示例展示其在實際開發中的應用價值。

本文旨在幫助開發者了解如何在 Go 項目中確定哪些文件會被編譯和鏈接,尤其是在存在特定於系統的文件時。我們將探討兩種方法:使用 go build -n 命令解析輸出,以及利用 go/build 包的 Import 函數。通過這些方法,您可以清晰地了解構建過程,並更好地管理您的項目。

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

本文旨在解決在使用 Go 語言進行 WebSocket 開發時遇到的 EOF (End-of-File) 錯誤。該錯誤通常發生在服務端接收到客戶端消息後,連接意外關閉,導致後續消息無法正常傳遞。本文將通過分析問題原因,提供代碼示例,並給出相應的解決方案,幫助開發者構建穩定可靠的 WebSocket 應用。

本文介紹瞭如何在 Go 程序中啟動外部編輯器(如 Vim 或 Nano),並等待用戶關閉編輯器後,程序繼續執行。通過設置 cmd.Stdin、cmd.Stdout 和 cmd.Stderr,使得編輯器能夠與終端進行交互,從而解決啟動失敗的問題。同時,展示了完整的代碼示例,並提供了注意事項,幫助開發者順利實現該功能。

struct{}是Go中無字段的結構體,佔用零字節,常用於無需數據傳遞的場景。它在通道中作信號使用,如goroutine同步;2.用作map的值類型模擬集合,實現高效內存的鍵存在性檢查;3.可定義無狀態的方法接收器,適用於依賴注入或組織函數。該類型廣泛用於表達控制流與清晰意圖。

MiddlewareinGowebserversarefunctionsthatinterceptHTTPrequestsbeforetheyreachthehandler,enablingreusablecross-cuttingfunctionality;theyworkbywrappinghandlerstoaddpre-andpost-processinglogicsuchaslogging,authentication,CORS,orerrorrecovery,andcanbechai

使用標準庫的encoding/json包讀取JSON配置文件;2.使用gopkg.in/yaml.v3庫讀取YAML格式配置;3.結合os.Getenv或godotenv庫使用環境變量覆蓋文件配置;4.使用Viper庫支持多格式配置、環境變量、自動重載等高級功能;必須定義結構體保證類型安全,妥善處理文件和解析錯誤,正確使用結構體標籤映射字段,避免硬編碼路徑,生產環境推薦使用環境變量或安全配置存儲,可從簡單的JSON開始,需求復雜時遷移到Viper。
