프로그래밍으로 이동 | 문자열 기초 | 문자 인코딩

WBOY
풀어 주다: 2024-08-12 12:35:43
원래의
839명이 탐색했습니다.

소개

Go Programming | String Basics | Character Encoding

이전 강의에서 우리는 Go의 문자가 UTF-8을 사용하여 인코딩되고 바이트 또는 룬 유형으로 저장된다는 것을 배웠습니다. 이제 문자 집합인 문자열에 대해 이야기해 보겠습니다. 함께 배워볼까요

지식 포인트:

  • 문자열이란 무엇입니까
  • 문자열 만들기
  • 문자열 선언
  • 일반적인 문자열 함수

문자열이란 무엇입니까?

Go에서 배운 첫 번째 프로그램에서는 hello, world라는 문자열을 인쇄했습니다.

문자열은 Go의 기본 데이터 유형으로 문자열 리터럴이라고도 합니다. 이는 문자의 집합으로 이해될 수 있으며 지속적인 메모리 블록을 차지합니다. 이 메모리 블록은 문자, 텍스트, 이모티콘 등 모든 유형의 데이터를 저장할 수 있습니다.

그러나 다른 언어와 달리 Go의 문자열은 읽기 전용이므로 수정할 수 없습니다.

문자열 만들기

문자열은 여러 가지 방법으로 선언할 수 있습니다. 첫 번째 방법을 살펴보겠습니다. string.go라는 새 파일을 만듭니다:

으아아아

다음 코드를 작성하세요:

으아아아

위 코드는 var 키워드와 := 연산자를 사용하여 문자열을 생성하는 방법을 보여줍니다. var로 변수 생성 시 값을 할당하면 변수 b 생성과 같이 타입 선언을 생략할 수 있습니다.

예상 출력은 다음과 같습니다.

으아아아

문자열 선언

대부분의 경우 문자열을 선언할 때 큰따옴표 ""를 사용합니다. 큰따옴표의 장점은 이스케이프 시퀀스로 사용할 수 있다는 것입니다. 예를 들어, 아래 프로그램에서는 n 이스케이프 시퀀스를 사용하여 새 줄을 만듭니다.

으아아아

예상 출력은 다음과 같습니다.

으아아아

다음은 몇 가지 일반적인 이스케이프 시퀀스입니다.

기호 설명
n 새로운 라인
r 운송 반납
t
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!