検索
ホームページバックエンド開発Golangプログラミングに行く |文字列の基本 |文字エンコーディング

導入

Go Programming | String Basics | Character Encoding

前のレッスンでは、Go の文字は UTF-8 を使用してエンコードされ、バイト型またはルーン型として保存されることを学びました。ここで、文字の集合である文字列について話しましょう。一緒に学びましょう

知識ポイント:

  • 文字列とは
  • 文字列を作成する
  • 文字列の宣言
  • 一般的な文字列関数

文字列とは

Go で学習した最初のプログラムでは、文字列 hello, world を出力しました。

String は Go の基本データ型であり、文字列リテラルとも呼ばれます。これは文字の集合として理解でき、メモリの連続ブロックを占有します。このメモリ ブロックには、文字、テキスト、絵文字など、あらゆる種類のデータを保存できます

ただし、他の言語とは異なり、Go の文字列は読み取り専用であり、変更できません。

文字列の作成

文字列はいくつかの方法で宣言できます。最初の方法を見てみましょう。 string.go という名前の新しいファイルを作成します:

リーリー

次のコードを書きます:

リーリー

上記のコードは、var キーワードと := 演算子を使用して文字列を作成する方法を示しています。 varで変数作成時に値を代入する場合は、変数bの作成のように型宣言を省略できます

期待される出力は次のとおりです:

リーリー

文字列の宣言

ほとんどの場合、文字列を宣言するには二重引用符 "" を使用します。二重引用符の利点は、エスケープ シーケンスとして使用できることです。たとえば、以下のプログラムでは、n エスケープ シーケンスを使用して新しい行を作成します:

リーリー

期待される出力は次のとおりです:

リーリー

一般的なエスケープ シーケンスをいくつか示します:

シンボル 説明
改行
r キャリッジリターン
タブ
b バックスペース
\ バックスラッシュ
' 単一引用符
二重引用符

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:

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))
}

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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
DebianでLibofficeのセキュリティ設定を行う方法DebianでLibofficeのセキュリティ設定を行う方法May 16, 2025 pm 01:24 PM

Debianシステムの全体的なセキュリティを確保することは、Libofficeなどのアプリケーションの実行環境を保護するために重要です。システムセキュリティを改善するための一般的な推奨事項を次に示します。システムの更新は、システムを定期的に更新して、既知のセキュリティの脆弱性をパッチします。 Debian12.10は、いくつかの重要なソフトウェアパッケージを含む多数のセキュリティの脆弱性を修正するセキュリティアップデートをリリースしました。ユーザー許可管理は、潜在的なセキュリティリスクを減らすために、日常業務にルートユーザーを使用することを回避します。通常のユーザーを作成し、SUDOグループに参加して、システムへの直接アクセスを制限することをお勧めします。 SSHサービスセキュリティ構成は、SSHキーペアを使用して、ルートリモートログインを認証、無効にし、空のパスワードでログインを制限します。これらの措置は、SSHサービスのセキュリティを強化し、

DebianでRustコンピレーションオプションを構成する方法DebianでRustコンピレーションオプションを構成する方法May 16, 2025 pm 01:21 PM

Debianシステムでの錆コンピレーションオプションの調整は、さまざまな方法で実現できます。以下は、いくつかの方法の詳細な説明です:Rustupツールを使用してRustupを構成およびインストールします。Rustupをまだインストールしていない場合は、次のコマンドを使用してインストールできます。設定コンピレーションオプション:Rustupを使用して、さまざまなツールチェーンとターゲットのコンパイルオプションを構成できます。 RustupoverRideコマンドを使用して、特定のプロジェクトのコンピレーションオプションを設定できます。たとえば、プロジェクトに特定の錆バージョンを設定する場合

DebianでKubernetesノードを管理する方法DebianでKubernetesノードを管理する方法May 16, 2025 pm 01:18 PM

Kubernetes(k8s)ノードの管理Debianシステムのノードの管理には、通常、次の重要な手順が含まれます。1。Kubernetesコンポーネントコンポーネントの設定準備:すべてのノード(マスターノードとワーカーノードを含む)がインストールされ、Kubernetes Clusterをインストールするための基本的な要件を満たしていることを確認してください。スワップパーティションの無効化:Kubeletがスムーズに実行できるようにするには、Swap Partitionを無効にすることをお勧めします。ファイアウォールルールの設定:Kubelet、Kube-Apiserver、Kube-Schedulerなどが使用するポートなど、必要なポートを許可します。

DebianのGolangのセキュリティ設定DebianのGolangのセキュリティ設定May 16, 2025 pm 01:15 PM

DebianにGolang環境を設定する場合、システムセキュリティを確保することが重要です。安全なGolang開発環境を構築するのに役立つ重要なセキュリティセットアップの手順と提案を次に示します。セキュリティセットアップステップシステムの更新:Golangをインストールする前にシステムが最新であることを確認してください。次のコマンドを使用して、システムパッケージリストとインストールパッケージを更新します。sudoaptupdatesudoaptupgrade-yファイアウォール構成:システムへのアクセスを制限するためにファイアウォール(iptablesなど)をインストールして構成します。必要なポート(HTTP、HTTPS、SSHなど)のみが許可されます。 sudoaptininstalliptablessud

Kubernetesの展開のパフォーマンスをDebianで最適化する方法Kubernetesの展開のパフォーマンスをDebianで最適化する方法May 16, 2025 pm 01:12 PM

DebianでKubernetesクラスターのパフォーマンスを最適化および展開することは、複数の側面を含む複雑なタスクです。主要な最適化戦略と提案を次に示します。ハードウェアリソース最適化CPU:十分なCPUリソースがKubernetesノードとポッドに割り当てられていることを確認してください。メモリ:特にメモリ集約型アプリケーションのノードのメモリ容量を増加させます。ストレージ:高性能SSDストレージを使用し、レイテンシを導入する可能性のあるネットワークファイルシステム(NFSなど)の使用を避けます。カーネルパラメーター最適化編集 /etc/sysctl.confファイル、次のパラメーターを追加または変更します:net.core.somaxconn:65535net.ipv4.tcp_max_syn

PythonスクリプトによるDebianでタスクをスケジュールする方法PythonスクリプトによるDebianでタスクをスケジュールする方法May 16, 2025 pm 01:09 PM

Debianシステムでは、Cronを使用して時限タスクを手配し、Pythonスクリプトの自動実行を実現できます。まず、端子を開始します。次のコマンドを入力して、現在のユーザーのCrontabファイルを編集します。Crontab-Eルートアクセス許可を持つ他のユーザーのCrontabファイルを編集する必要がある場合は、編集するユーザー名にユーザー名を置き換えるために、sudocrontab-uusername-eを使用してください。 crontabファイルでは、次のように形式のタイミングされたタスクを追加できます:*****/path/to/your/python-script.pyこれら5つのアスタリスクは議事録(0-59)以降を表します

DebianでGolangネットワークパラメーターを構成する方法DebianでGolangネットワークパラメーターを構成する方法May 16, 2025 pm 01:06 PM

DebianシステムでGolangのネットワークパラメーターを調整することは、さまざまな方法で実現できます。以下はいくつかの実行可能な方法です。方法1:環境変数を設定することにより、環境変数を一時的に設定します。端末に次のコマンドを入力して、環境変数を一時的に設定します。この設定は、現在のセッションでのみ有効です。 ExportGodeBug = "GCTRACE = 1NETDNS = GO" GCTRACE = 1はガベージコレクション追跡をアクティブにし、NetDNS = GOはシステムのデフォルトではなく独自のDNSリゾルバーを使用します。環境変数を永続的に設定します:〜/.bashrcや〜/.profileなどのシェル構成ファイルに上記のコマンドを追加します

DebianのLibofficeのショートカットキーは何ですかDebianのLibofficeのショートカットキーは何ですかMay 16, 2025 pm 01:03 PM

DebianシステムでLibofficeをカスタマイズするためのショートカットキーは、システム設定を通じて調整できます。 Libofficeショートカットキーを設定するための一般的に使用される手順と方法を次に示します。Libofficeショートカットキーを設定するための基本的な手順オープンシステム設定:Debianシステムで、左上隅のメニュー(通常ギアアイコン)をクリックし、「システム設定」を選択します。 [デバイス]を選択します。[システム設定]ウィンドウで、[デバイス]を選択します。キーボードを選択します。デバイス設定ページで、キーボードを選択します。対応するツールへのコマンドを見つけます。キーボード設定ページで、下にスクロールして「ショートカットキー」オプションを表示します。クリックすると、ポップアップにウィンドウが表示されます。ポップアップウィンドウで対応するLibofficeワーカーを見つけます

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境