pengenalan
Dalam pelajaran sebelumnya, kita mengetahui bahawa aksara dalam Go dikodkan menggunakan UTF-8 dan disimpan sebagai sama ada jenis bait atau rune. Sekarang, mari kita bercakap tentang rentetan, yang merupakan koleksi aksara. Mari belajar tentangnya bersama-sama.
Mata Pengetahuan:
- Apakah rentetan
- Membuat rentetan
- Mengisytiharkan rentetan
- Fungsi rentetan biasa
Apa itu String
Dalam program pertama yang kami pelajari dalam Go, kami mencetak rentetan hello, world.
String ialah jenis data asas dalam Go, juga dikenali sebagai literal rentetan. Ia boleh difahami sebagai koleksi aksara dan menduduki blok memori yang berterusan. Blok memori ini boleh menyimpan sebarang jenis data, seperti huruf, teks, emoji, dll.
Walau bagaimanapun, tidak seperti bahasa lain, rentetan dalam Go adalah baca sahaja dan tidak boleh diubah suai.
Mencipta Rentetan
String boleh diisytiharkan dalam beberapa cara. Mari kita lihat kaedah pertama. Buat fail baharu bernama string.go:
touch ~/project/string.go
Tulis kod berikut:
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) }
Kod di atas menunjukkan cara membuat rentetan menggunakan kata kunci var dan pengendali :=. Jika anda menetapkan nilai semasa membuat pembolehubah dengan var, anda boleh meninggalkan pengisytiharan jenis, seperti yang ditunjukkan dalam penciptaan pembolehubah b.
Keluaran yang dijangkakan adalah seperti berikut:
labex shiyanlou Monday Hangzhou
Mengisytiharkan Rentetan
Dalam kebanyakan kes, kami menggunakan petikan berganda "" untuk mengisytiharkan rentetan. Kelebihan petikan berganda ialah ia boleh digunakan sebagai urutan pelarian. Contohnya, dalam atur cara di bawah, kami menggunakan jujukan n escape untuk mencipta baris baharu:
package main import "fmt" func main(){ x := "shiyanlou\nlabex" fmt.Println(x) }
Keluaran yang dijangkakan adalah seperti berikut:
shiyanlou labex
Berikut ialah beberapa urutan pelarian biasa:
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
Atas ialah kandungan terperinci Pergi Pengaturcaraan | Asas Rentetan | Pengekodan aksara. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Golang cemerlang dalam aplikasi praktikal dan terkenal dengan kesederhanaan, kecekapan dan kesesuaiannya. 1) Pengaturcaraan serentak dilaksanakan melalui goroutine dan saluran, 2) Kod fleksibel ditulis menggunakan antara muka dan polimorfisme, 3) memudahkan pengaturcaraan rangkaian dengan pakej bersih/HTTP, 4) Membina crawler serentak yang cekap, 5) Debugging dan mengoptimumkan melalui alat dan amalan terbaik.

Ciri -ciri teras GO termasuk pengumpulan sampah, penyambungan statik dan sokongan konvensional. 1. Model keseragaman bahasa GO menyedari pengaturcaraan serentak yang cekap melalui goroutine dan saluran. 2. Antara muka dan polimorfisme dilaksanakan melalui kaedah antara muka, supaya jenis yang berbeza dapat diproses secara bersatu. 3. Penggunaan asas menunjukkan kecekapan definisi fungsi dan panggilan. 4. Dalam penggunaan lanjutan, kepingan memberikan fungsi saiz semula dinamik yang kuat. 5. Kesilapan umum seperti keadaan kaum dapat dikesan dan diselesaikan melalui perlumbaan getest. 6. Pengoptimuman prestasi menggunakan objek melalui sync.pool untuk mengurangkan tekanan pengumpulan sampah.

Pergi bahasa berfungsi dengan baik dalam membina sistem yang cekap dan berskala. Kelebihannya termasuk: 1. Prestasi Tinggi: Disusun ke dalam Kod Mesin, Kelajuan Berjalan Cepat; 2. Pengaturcaraan serentak: Memudahkan multitasking melalui goroutine dan saluran; 3. Kesederhanaan: sintaks ringkas, mengurangkan kos pembelajaran dan penyelenggaraan; 4. Cross-Platform: Menyokong kompilasi silang platform, penggunaan mudah.

Keliru mengenai penyortiran hasil pertanyaan SQL. Dalam proses pembelajaran SQL, anda sering menghadapi beberapa masalah yang mengelirukan. Baru-baru ini, penulis membaca "Asas Mick-SQL" ...

Hubungan antara konvergensi stack teknologi dan pemilihan teknologi dalam pembangunan perisian, pemilihan dan pengurusan susunan teknologi adalah isu yang sangat kritikal. Baru -baru ini, beberapa pembaca telah mencadangkan ...

Golang ...

Bagaimana membandingkan dan mengendalikan tiga struktur dalam bahasa Go. Dalam pengaturcaraan GO, kadang -kadang perlu untuk membandingkan perbezaan antara dua struktur dan menggunakan perbezaan ini kepada ...

Bagaimana untuk melihat pakej yang dipasang di seluruh dunia? Dalam proses membangun dengan bahasa Go, sering menggunakan ...


Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

AI Hentai Generator
Menjana ai hentai secara percuma.

Artikel Panas

Alat panas

SecLists
SecLists ialah rakan penguji keselamatan muktamad. Ia ialah koleksi pelbagai jenis senarai yang kerap digunakan semasa penilaian keselamatan, semuanya di satu tempat. SecLists membantu menjadikan ujian keselamatan lebih cekap dan produktif dengan menyediakan semua senarai yang mungkin diperlukan oleh penguji keselamatan dengan mudah. Jenis senarai termasuk nama pengguna, kata laluan, URL, muatan kabur, corak data sensitif, cangkerang web dan banyak lagi. Penguji hanya boleh menarik repositori ini ke mesin ujian baharu dan dia akan mempunyai akses kepada setiap jenis senarai yang dia perlukan.

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

EditPlus versi Cina retak
Saiz kecil, penyerlahan sintaks, tidak menyokong fungsi gesaan kod

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

VSCode Windows 64-bit Muat Turun
Editor IDE percuma dan berkuasa yang dilancarkan oleh Microsoft