소개
이전 강의에서 우리는 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:
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

보안 통신에 널리 사용되는 오픈 소스 라이브러리로서 OpenSSL은 암호화 알고리즘, 키 및 인증서 관리 기능을 제공합니다. 그러나 역사적 버전에는 알려진 보안 취약점이 있으며 그 중 일부는 매우 유해합니다. 이 기사는 데비안 시스템의 OpenSSL에 대한 일반적인 취약점 및 응답 측정에 중점을 둘 것입니다. DebianopensSL 알려진 취약점 : OpenSSL은 다음과 같은 몇 가지 심각한 취약점을 경험했습니다. 심장 출혈 취약성 (CVE-2014-0160) :이 취약점은 OpenSSL 1.0.1 ~ 1.0.1F 및 1.0.2 ~ 1.0.2 베타 버전에 영향을 미칩니다. 공격자는이 취약점을 사용하여 암호화 키 등을 포함하여 서버에서 무단 읽기 민감한 정보를 사용할 수 있습니다.

이 기사는 프로파일 링 활성화, 데이터 수집 및 CPU 및 메모리 문제와 같은 일반적인 병목 현상을 식별하는 등 GO 성능 분석을 위해 PPROF 도구를 사용하는 방법을 설명합니다.

이 기사는 GO에서 단위 테스트 작성, 모범 사례, 조롱 기술 및 효율적인 테스트 관리를위한 도구를 다루는 것에 대해 논의합니다.

이 기사는 단위 테스트를 위해 이동 중에 모의와 스터브를 만드는 것을 보여줍니다. 인터페이스 사용을 강조하고 모의 구현의 예를 제공하며 모의 집중 유지 및 어설 션 라이브러리 사용과 같은 모범 사례에 대해 설명합니다. 기사

이 기사에서는 GO의 제네릭에 대한 사용자 정의 유형 제약 조건을 살펴 봅니다. 인터페이스가 일반 함수에 대한 최소 유형 요구 사항을 정의하여 유형 안전 및 코드 재사성을 향상시키는 방법에 대해 자세히 설명합니다. 이 기사는 또한 한계와 모범 사례에 대해 설명합니다

이 기사는 코드의 런타임 조작, 직렬화, 일반 프로그래밍에 유리한 런타임 조작에 사용되는 GO의 반사 패키지에 대해 설명합니다. 실행 속도가 느리고 메모리 사용이 높아짐, 신중한 사용 및 최고와 같은 성능 비용을 경고합니다.

이 기사는 추적 도구를 사용하여 GO 응용 프로그램 실행 흐름을 분석합니다. 수동 및 자동 계측 기술, Jaeger, Zipkin 및 OpenTelemetry와 같은 도구 비교 및 효과적인 데이터 시각화를 강조합니다.

이 기사는 테스트 케이스 테이블을 사용하여 여러 입력 및 결과로 기능을 테스트하는 방법 인 GO에서 테이블 중심 테스트를 사용하는 것에 대해 설명합니다. 가독성 향상, 중복 감소, 확장 성, 일관성 및 A와 같은 이점을 강조합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Dreamweaver Mac版
시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.
