検索
ホームページバックエンド開発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 OpenSSLの脆弱性は何ですかDebian OpenSSLの脆弱性は何ですかApr 02, 2025 am 07:30 AM

OpenSSLは、安全な通信で広く使用されているオープンソースライブラリとして、暗号化アルゴリズム、キー、証明書管理機能を提供します。ただし、その歴史的バージョンにはいくつかの既知のセキュリティの脆弱性があり、その一部は非常に有害です。この記事では、Debian SystemsのOpenSSLの共通の脆弱性と対応測定に焦点を当てます。 Debianopensslの既知の脆弱性:OpenSSLは、次のようないくつかの深刻な脆弱性を経験しています。攻撃者は、この脆弱性を、暗号化キーなどを含む、サーバー上の不正な読み取りの敏感な情報に使用できます。

PPROFツールを使用してGOパフォーマンスを分析しますか?PPROFツールを使用してGOパフォーマンスを分析しますか?Mar 21, 2025 pm 06:37 PM

この記事では、プロファイリングの有効化、データの収集、CPUやメモリの問題などの一般的なボトルネックの識別など、GOパフォーマンスを分析するためにPPROFツールを使用する方法について説明します。

Goでユニットテストをどのように書きますか?Goでユニットテストをどのように書きますか?Mar 21, 2025 pm 06:34 PM

この記事では、GOでユニットテストを書くことで、ベストプラクティス、モッキングテクニック、効率的なテスト管理のためのツールについて説明します。

GOでテスト用のモックオブジェクトとスタブを書くにはどうすればよいですか?GOでテスト用のモックオブジェクトとスタブを書くにはどうすればよいですか?Mar 10, 2025 pm 05:38 PM

この記事では、ユニットテストのためにGOのモックとスタブを作成することを示しています。 インターフェイスの使用を強調し、模擬実装の例を提供し、模擬フォーカスを維持し、アサーションライブラリを使用するなどのベストプラクティスについて説明します。 articl

GOのジェネリックのカスタムタイプ制約を定義するにはどうすればよいですか?GOのジェネリックのカスタムタイプ制約を定義するにはどうすればよいですか?Mar 10, 2025 pm 03:20 PM

この記事では、GENICSのGOのカスタムタイプの制約について説明します。 インターフェイスがジェネリック関数の最小タイプ要件をどのように定義するかを詳しく説明し、タイプの安全性とコードの再利用性を改善します。 この記事では、制限とベストプラクティスについても説明しています

Goの反射パッケージの目的を説明してください。いつリフレクションを使用しますか?パフォーマンスへの影響は何ですか?Goの反射パッケージの目的を説明してください。いつリフレクションを使用しますか?パフォーマンスへの影響は何ですか?Mar 25, 2025 am 11:17 AM

この記事では、コードのランタイム操作に使用されるGoの反射パッケージについて説明します。シリアル化、一般的なプログラミングなどに有益です。実行やメモリの使用量の増加、賢明な使用と最高のアドバイスなどのパフォーマンスコストについて警告します

トレースツールを使用して、GOアプリケーションの実行フローを理解するにはどうすればよいですか?トレースツールを使用して、GOアプリケーションの実行フローを理解するにはどうすればよいですか?Mar 10, 2025 pm 05:36 PM

この記事では、トレースツールを使用してGOアプリケーションの実行フローを分析します。 手動および自動計装技術について説明し、Jaeger、Zipkin、Opentelemetryなどのツールを比較し、効果的なデータの視覚化を強調しています

GOでテーブル駆動型テストをどのように使用しますか?GOでテーブル駆動型テストをどのように使用しますか?Mar 21, 2025 pm 06:35 PM

この記事では、GOでテーブル駆動型のテストを使用して説明します。これは、テストのテーブルを使用して複数の入力と結果を持つ関数をテストする方法です。読みやすさの向上、重複の減少、スケーラビリティ、一貫性、および

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衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン