Heim Backend-Entwicklung Golang Gehen Sie zum Programmieren | String-Grundlagen | Zeichenkodierung

Gehen Sie zum Programmieren | String-Grundlagen | Zeichenkodierung

Aug 12, 2024 pm 12:35 PM

Einführung

Go Programming | String Basics | Character Encoding

In der vorherigen Lektion haben wir gelernt, dass Zeichen in Go mit UTF-8 codiert und entweder als Byte- oder Rune-Typ gespeichert werden. Lassen Sie uns nun über Zeichenfolgen sprechen, bei denen es sich um eine Sammlung von Zeichen handelt. Lasst uns gemeinsam etwas darüber lernen.

Wissenspunkte:

  • Was ist eine Zeichenfolge?
  • Erstellen einer Zeichenfolge
  • Deklarieren einer Zeichenfolge
  • Gemeinsame String-Funktionen

Was ist ein String?

Im ersten Programm, das wir in Go gelernt haben, haben wir die Zeichenfolge „hello, world“ gedruckt.

String ist ein grundlegender Datentyp in Go, auch bekannt als String-Literal. Es kann als eine Sammlung von Zeichen verstanden werden und belegt einen kontinuierlichen Speicherblock. Dieser Speicherblock kann jede Art von Daten speichern, z. B. Buchstaben, Text, Emojis usw.

Im Gegensatz zu anderen Sprachen sind Zeichenfolgen in Go jedoch schreibgeschützt und können nicht geändert werden.

Erstellen einer Zeichenfolge

Strings können auf verschiedene Arten deklariert werden. Werfen wir einen Blick auf die erste Methode. Erstellen Sie eine neue Datei mit dem Namen string.go:

touch ~/project/string.go
Nach dem Login kopieren

Schreiben Sie den folgenden Code:

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)
}
Nach dem Login kopieren

Der obige Code zeigt, wie Zeichenfolgen mit dem Schlüsselwort var und dem Operator := erstellt werden. Wenn Sie beim Erstellen einer Variablen mit var einen Wert zuweisen, können Sie die Typdeklaration weglassen, wie bei der Erstellung der Variablen b gezeigt.

Die erwartete Ausgabe ist wie folgt:

labex shiyanlou Monday Hangzhou
Nach dem Login kopieren

Einen String deklarieren

In den meisten Fällen verwenden wir doppelte Anführungszeichen „“, um Zeichenfolgen zu deklarieren. Der Vorteil doppelter Anführungszeichen besteht darin, dass sie als Escape-Sequenz verwendet werden können. Im folgenden Programm verwenden wir beispielsweise die Escape-Sequenz n, um eine neue Zeile zu erstellen:

package main

import "fmt"

func main(){
    x := "shiyanlou\nlabex"
    fmt.Println(x)
}
Nach dem Login kopieren

Die erwartete Ausgabe ist wie folgt:

shiyanlou
labex
Nach dem Login kopieren

Hier sind einige gängige Escape-Sequenzen:

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)
}
Nach dem Login kopieren

After running the program, you will see the following output:

Go Programming | String Basics | Character Encoding

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))
}
Nach dem Login kopieren

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
Nach dem Login kopieren

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
}
Nach dem Login kopieren

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
Nach dem Login kopieren

In the program, we use the Sprintf() function from the fmt package, which has the following format:

func Sprintf(format string, a ...interface{}) string
Nach dem Login kopieren

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
Nach dem Login kopieren

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
}

Nach dem Login kopieren

The expected output is as follows:

lan qiao labex labex
Nach dem Login kopieren

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
Nach dem Login kopieren

Here is an example:

package main

import (
    "fmt"
    "strings"
)

func main() {
    a := " \t \n  labex \n \t hangzhou"
    fmt.Println(strings.TrimSpace(a))
}
Nach dem Login kopieren

The expected output is as follows:

labex
    hangzhou
Nach dem Login kopieren

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

Das obige ist der detaillierte Inhalt vonGehen Sie zum Programmieren | String-Grundlagen | Zeichenkodierung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

<🎜>: Bubble Gum Simulator Infinity - So erhalten und verwenden Sie Royal Keys
4 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusionssystem, erklärt
4 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Flüstern des Hexenbaum
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

Java-Tutorial
1676
14
PHP-Tutorial
1278
29
C#-Tutorial
1257
24
Golang gegen Python: Leistung und Skalierbarkeit Golang gegen Python: Leistung und Skalierbarkeit Apr 19, 2025 am 12:18 AM

Golang ist in Bezug auf Leistung und Skalierbarkeit besser als Python. 1) Golangs Kompilierungseigenschaften und effizientes Parallelitätsmodell machen es in hohen Parallelitätsszenarien gut ab. 2) Python wird als interpretierte Sprache langsam ausgeführt, kann aber die Leistung durch Tools wie Cython optimieren.

Golang und C: Parallelität gegen Rohgeschwindigkeit Golang und C: Parallelität gegen Rohgeschwindigkeit Apr 21, 2025 am 12:16 AM

Golang ist in Gleichzeitigkeit besser als C, während C bei Rohgeschwindigkeit besser als Golang ist. 1) Golang erreicht durch Goroutine und Kanal eine effiziente Parallelität, die zum Umgang mit einer großen Anzahl von gleichzeitigen Aufgaben geeignet ist. 2) C über Compiler -Optimierung und Standardbibliothek bietet es eine hohe Leistung in der Nähe der Hardware, die für Anwendungen geeignet ist, die eine extreme Optimierung erfordern.

Erste Schritte mit Go: Ein Anfängerführer Erste Schritte mit Go: Ein Anfängerführer Apr 26, 2025 am 12:21 AM

GoisidealforBeginersandSuitableforCloudandNetWorkServicesDuetoitsSimplicity, Effizienz und Konsumfeaturen.1) InstallgoFromTheofficialwebSiteAnDverifyWith'goversion'.2) CreateAneDrunyourFirstProgramwith'gorunhello.go.go.go.

Golang gegen C: Leistung und Geschwindigkeitsvergleich Golang gegen C: Leistung und Geschwindigkeitsvergleich Apr 21, 2025 am 12:13 AM

Golang ist für schnelle Entwicklung und gleichzeitige Szenarien geeignet, und C ist für Szenarien geeignet, in denen extreme Leistung und Kontrolle auf niedriger Ebene erforderlich sind. 1) Golang verbessert die Leistung durch Müllsammlung und Parallelitätsmechanismen und eignet sich für die Entwicklung von Webdiensten mit hoher Konsequenz. 2) C erreicht die endgültige Leistung durch das manuelle Speicherverwaltung und die Compiler -Optimierung und eignet sich für eingebettete Systementwicklung.

Golang gegen Python: Schlüsselunterschiede und Ähnlichkeiten Golang gegen Python: Schlüsselunterschiede und Ähnlichkeiten Apr 17, 2025 am 12:15 AM

Golang und Python haben jeweils ihre eigenen Vorteile: Golang ist für hohe Leistung und gleichzeitige Programmierung geeignet, während Python für Datenwissenschaft und Webentwicklung geeignet ist. Golang ist bekannt für sein Parallelitätsmodell und seine effiziente Leistung, während Python für sein Ökosystem für die kurze Syntax und sein reiches Bibliothek bekannt ist.

Golang und C: Die Kompromisse bei der Leistung Golang und C: Die Kompromisse bei der Leistung Apr 17, 2025 am 12:18 AM

Die Leistungsunterschiede zwischen Golang und C spiegeln sich hauptsächlich in der Speicherverwaltung, der Kompilierungsoptimierung und der Laufzeiteffizienz wider. 1) Golangs Müllsammlung Mechanismus ist praktisch, kann jedoch die Leistung beeinflussen.

Das Performance -Rennen: Golang gegen C. Das Performance -Rennen: Golang gegen C. Apr 16, 2025 am 12:07 AM

Golang und C haben jeweils ihre eigenen Vorteile bei Leistungswettbewerben: 1) Golang ist für eine hohe Parallelität und schnelle Entwicklung geeignet, und 2) C bietet eine höhere Leistung und eine feinkörnige Kontrolle. Die Auswahl sollte auf Projektanforderungen und Teamtechnologie -Stack basieren.

Golang gegen Python: Die Vor- und Nachteile Golang gegen Python: Die Vor- und Nachteile Apr 21, 2025 am 12:17 AM

GolangissidealforbuildingsCalablesSystemduetoitseffizienz und Konsumverkehr, whilepythonexcelsinquickScriptingandDataanalyseduetoitssimplication und VacevastEcosystem.golangsDesineScouragesCouragescournations, tadelcodedeanDitsGoroutaTinoutgoroutaTinoutgoroutaTinoutsGoroutinesGoroutinesGoroutsGoroutins, t

See all articles