English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
in Go language, strings are different from other languages such as Java, c++、Python, etc. It is a variable-width character sequence, where each character is represented by UTF-8encoding, one or more bytes represent. Or in other words, a string is an immutable chain of arbitrary bytes (including bytes with a value of zero), or a string is a read-only byte slice, the bytes of the string can be represented by UTF-8encoding to represent Unicode text.
Since it uses UTF-8Encoding, Golang strings can contain text, text is a mixture of any language in the world without causing chaos and restrictions on the page. Usually, strings are usedDouble quotes””Quoted, as shown in the following examples:
//How to create a string package main import "fmt" func main() { //(原始文本)。原始文本不支持转义字符,可以跨越多行,并且可以包含除反引号之外的任何字符。通常,它用于在正则表达式和HTML中编写多行消息。 //Variables with strings //usar declaração abreviada My_value_1 := "Welcome to oldtoolbag.com" //Using the var keyword var My_value_2 string My_value_2 = "w3codebox" //exibir a string fmt.Println("String 1: ", My_value_1) fmt.Println("String 2: ", My_value_2) }
saída:
String 1: Welcome to oldtoolbag.com String 2: w3codebox
Note:A string can be empty, but cannot be nil.
In Go language, string literals are created in two different ways:
Using double quotes (""):Here, string literals are created using double quotes (""). This type of string literal supports escape characters, as shown in the following table, but does not span multiple lines. This type of string literal is widely used in Golang programs.
Escape character | Description |
---|---|
\\\ | Backslash (\) |
\000 | \xhh3具有给定的8Unicode character with bit octal code point |
\' | Single quotes ('). They are only allowed to be used in character literals. |
\” | Double quotes (""). They are only allowed to be used in interpreted string literals. |
\a | Bell (BEL) |
\b | Backspace (BS) |
\f | Form Feed (FF) |
\n | Line Feed (LF) |
\r | Carriage Return (CR) |
\t | Horizontal Tab (HT) |
\uhhhh | \xhh4具有给定的16位 |
\xhh8具有给定的32位 | |
\v | Carriage Return (CR) |
\xhh | \xhh2具有给定的8位 |
位十六进制代码点的Unicode字符。使用反引号(``):此处,字符串文字是使用反引号(``)创建的,也称为raw literals
package main import "fmt" func main() { //(原始文本)。原始文本不支持转义字符,可以跨越多行,并且可以包含除反引号之外的任何字符。通常,它用于在正则表达式和HTML中编写多行消息。 //创建并初始化 //带有字符串文字的变量 My_value_1 := "Welcome to w3codebox" //添加转义字符 My_value_2 := "Welcome to w3codebox" //:= "Welcome!\nw My_value_3 := `Hello!w3codebox` //添加转义字符 //原始文本 My_value_4 := `Hello!\nw3codebox` //显示 fmt.Println("String 1: ", My_value_1) fmt.Println("String 2: ", My_value_2) fmt.Println("String 3: ", My_value_3) fmt.Println("String 4: ", My_value_4) }
saída:
String 1: Welcome to w3codebox String 2: Welcome! w3codebox String 3: Hello!w3codebox String 4: Hello!\nw3codebox
字符串是不可变的:在Go语言中,一旦创建了字符串,则字符串是不可变的,无法更改字符串的值。换句话说,字符串是只读的。如果尝试更改,则编译器将引发错误。
//字符串是不可变的 package main import "fmt" func main() { //criar e inicializar uma string //usar declaração abreviada mystr := "Welcome to w3codebox" fmt.Println("String:", mystr) /* 果你试图改变字符串的值,编译器将抛出一个错误,例如, cannot assign to mystr[1] mystr[1= 'G' fmt.Println("String:", mystr) */ }
saída:
String: Welcome to w3codebox
如何遍历字符串?:您可以使用for range循环遍历字符串。此循环可以在Unicode代码点上迭代一个字符串。
语法:
for index, chr:= range str{ // 语句.. }
在这里,索引是存储UTF-8编码代码点的第一个字节的变量,而chr是存储给定字符串的字符的变量,str是字符串。
//遍历字符串 //使用for范围循环 package main import "fmt" func main() { //字符串作为for循环中的范围 for index, s := range "w3codebox" { fmt.Printf("%c 索引值是 %d\n", s, index) } }
saída:
n 索引值是 0 h 索引值是 1 o 索引值是 2 o 索引值是 3 o 索引值是 4
如何访问字符串的单个字节?:字符串是一个字节,因此,我们可以访问给定字符串的每个字节。
//访问字符串的字节 package main import "fmt" func main() { //创建和初始化一个字符串 str := "Welcome to w3codebox" //acessar o byte da string especificada for c := 0; c < len(str); c++ { fmt.Printf("\ncaractere = %c byte = %v", str[c], str[c]) } }
saída:
caractere = W byte = 87 caractere = e byte = 101 caractere = l byte = 108 caractere = c byte = 99 caractere = o byte = 111 caractere = m byte = 109 caractere = e byte = 101 caractere = byte = 32 caractere = t byte = 116 caractere = o byte = 111 caractere = byte = 32 caractere = n byte = 110 caractere = h byte = 104 caractere = o byte = 111 caractere = o byte = 111 caractere = o byte = 111
como criar uma string a partir de um fatia?:No idioma Go, você pode criar uma string a partir de um fatia de bytes.
//criar uma string a partir de um fatia package main import "fmt" func main() { //criar e inicializar um fatia de bytes myslice1 := []byte{0x47, 0x65, 0x65, 0x6b, 0x73} //criar uma string a partir de um fatia mystring1 := string(myslice1) //exibir a string fmt.Println("String 1: ", mystring1) //criar e inicializar um fatia de caracteres myslice2 := []rune{0x0047, 0x0065, 0x0065, 0x006b, 0x0073} //criar uma string a partir de um fatia mystring2 := string(myslice2) //exibir a string fmt.Println("String 2: ", mystring2) }
saída:
String 1: Geeks String 2: Geeks
como encontrar o comprimento da string?:No Go strings, você pode usar duas funções (uma élen(),outro éRuneCountInString())para encontrar o comprimento da string. UTF-8o pacote oferece a função RuneCountInString() que retorna o número total de caracteres existentes na string.len()a função retorna o número de bytes da string.
//procurar o comprimento da string package main import (" "fmt" "unicode/utf8" ) func main() { //criar e inicializar uma string //usar declaração abreviada mystr := "Welcome to w3codebox ??????" //procurar o comprimento da string //usar a função len() length1 := len(mystr) //usar a função RuneCountInString() length2 := utf8.RuneCountInString(mystr) //exibir o comprimento da string fmt.Println("string:", mystr) fmt.Println("Tamanho 1:", length1) fmt.Println("Tamanho 2:", length2) }
saída:
string: Welcome to w3codebox ?????? Comprimento 1: 31 Comprimento 2: 31