📜  Golang 中的字符串

📅  最后修改于: 2021-10-24 13:34:51             🧑  作者: Mango

在 Go 语言中,字符串不同于Java、C++、 Python等其他语言。它是一个可变宽度字符序列,其中每个字符都使用 UTF-8 编码由一个或多个字节表示。或者换句话说,字符串是任意字节(包括具有零值的字节)的不可变链,或者字符串是字节的只读切片,字符串的字节可以使用 UTF-8 编码在 Unicode 文本中表示。
由于 UTF-8 编码,Golang字符串可以包含世界上任何语言的混合文本,而不会对页面造成任何混淆和限制。通常,字符串用双引号””括起来,如下例所示:

例子:

// Go program to illustrate
// how to create strings
package main
  
import "fmt"
  
func main() {
  
    // Creating and initializing a
    // variable with a string
    // Using shorthand declaration
    My_value_1 := "Welcome to GeeksforGeeks"
  
    // Using var keyword
    var My_value_2 string
    My_value_2 = "GeeksforGeeks"
  
    // Displaying strings
    fmt.Println("String 1: ", My_value_1)
    fmt.Println("String 2: ", My_value_2)
}

输出:

String 1:  Welcome to GeeksforGeeks
String 2:  GeeksforGeeks

注意:字符串可以为空,但不能为空。

字符串字面量

在 Go 语言中,字符串字面量以两种不同的方式创建:

  • 使用双引号(“”):这里,字符串字面量是使用双引号(“”)创建的。这种类型的字符串支持如下表所示的转义字符,但不跨越多行。这种类型的字符串字面量在 Golang 程序中被广泛使用。
    Escape character Description
    \\ Backslash(\)
    \000 Unicode character with the given 3-digit 8-bit octal code point
    \’ Single quote (‘). It is only allowed inside character literals
    \” Double quote (“). It is only allowed inside interpreted string literals
    \a ASCII bell (BEL)
    \b ASCII backspace (BS)
    \f ASCII formfeed (FF)
    \n ASCII linefeed (LF
    \r ASCII carriage return (CR)
    \t ASCII tab (TAB)
    \uhhhh Unicode character with the given 4-digit 16-bit hex code point.
    Unicode character with the given 8-digit 32-bit hex code point.
    \v ASCII vertical tab (VT)
    \xhh Unicode character with the given 2-digit 8-bit hex code point.
  • 使用反引号(“):这里,字符串字面量是使用反引号(“)创建的,也称为raw literals 。原始字面量不支持转义字符,可以跨越多行,并且可以包含除反引号之外的任何字符。它通常用于在正则表达式和 HTML 中编写多行消息。

    例子:

    // Go program to illustrate string literals
    package main
      
    import "fmt"
      
    func main() {
      
        // Creating and initializing a
        // variable with a string literal
        // Using double-quote
        My_value_1 := "Welcome to GeeksforGeeks"
      
        // Adding escape character
        My_value_2 := "Welcome!\nGeeksforGeeks"
      
        // Using backticks
        My_value_3 := `Hello!GeeksforGeeks`
      
        // Adding escape character
        // in raw literals
        My_value_4 := `Hello!\nGeeksforGeeks`
      
        // Displaying strings
        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)
    }
    

    输出:

    String 1:  Welcome to GeeksforGeeks
    String 2:  Welcome!
    GeeksforGeeks
    String 3:  Hello!GeeksforGeeks
    String 4:  Hello!\nGeeksforGeeks
    

关于字符串的要点

  • 字符串是不可变的:在围棋的语言,一旦字符串创建的字符串的值不能被改变的字符串是不可变的。或者换句话说,字符串是只读的。如果您尝试更改,那么编译器将抛出错误。

    例子:

    // Go program to illustrate
    // string are immutable
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a string
        // using shorthand declaration
        mystr := "Welcome to GeeksforGeeks"
      
        fmt.Println("String:", mystr)
      
        /* if you trying to change
              the value of the string
              then the compiler will
              throw an error, i.e,
             cannot assign to mystr[1]
      
           mystr[1]= 'G'
           fmt.Println("String:", mystr)
        */
      
    }
    

    输出:

    String: Welcome to GeeksforGeeks
  • 如何迭代字符串?:您可以使用 for rang 循环迭代字符串。此循环可以遍历字符串的 Unicode 代码点。

    句法:

    for index, chr:= range str{
         // Statement..
    }
    

    这里,该索引是存储UTF-8编码码点的第一个字节和CHR存储给定字符串的各字符和STR是一个字符串变量。

    例子:

    // Go program to illustrate how
    // to iterate over the string
    // using for range loop
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // String as a range in the for loop
        for index, s := range "GeeksForGeeKs" {
          
            fmt.Printf("The index number of %c is %d\n", s, index)
        }
    }
    

    输出:

    The index number of G is 0
    The index number of e is 1
    The index number of e is 2
    The index number of k is 3
    The index number of s is 4
    The index number of F is 5
    The index number of o is 6
    The index number of r is 7
    The index number of G is 8
    The index number of e is 9
    The index number of e is 10
    The index number of K is 11
    The index number of s is 12
    
  • 如何访问字符串的单个字节?:字符串是一个字节,所以我们可以访问给定字符串的每个字节。

    例子:

    // Go program to illustrate how to
    // access the bytes of the string
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a string
        str := "Welcome to GeeksforGeeks"
      
        // Accessing the bytes of the given string
        for c := 0; c < len(str); c++ {
      
            fmt.Printf("\nCharacter = %c Bytes = %v", str, str)
        }
    }
    

    输出:

    Character = W Bytes = 87
    Character = e Bytes = 101
    Character = l Bytes = 108
    Character = c Bytes = 99
    Character = o Bytes = 111
    Character = m Bytes = 109
    Character = e Bytes = 101
    Character =   Bytes = 32
    Character = t Bytes = 116
    Character = o Bytes = 111
    Character =   Bytes = 32
    Character = G Bytes = 71
    Character = e Bytes = 101
    Character = e Bytes = 101
    Character = k Bytes = 107
    Character = s Bytes = 115
    Character = f Bytes = 102
    Character = o Bytes = 111
    Character = r Bytes = 114
    Character = G Bytes = 71
    Character = e Bytes = 101
    Character = e Bytes = 101
    Character = k Bytes = 107
    Character = s Bytes = 115
    
  • 如何从切片创建字符串?:在 Go 语言中,您可以从字节切片创建字符串。

    例子:

    // Go program to illustrate how to
    // create a string from the slice
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating and initializing a slice of byte
        myslice1 := []byte{0x47, 0x65, 0x65, 0x6b, 0x73}
      
        // Creating a string from the slice
        mystring1 := string(myslice1)
      
        // Displaying the string
        fmt.Println("String 1: ", mystring1)
      
        // Creating and initializing a slice of rune
        myslice2 := []rune{0x0047, 0x0065, 0x0065, 
                                   0x006b, 0x0073}
      
        // Creating a string from the slice
        mystring2 := string(myslice2)
      
        // Displaying the string
        fmt.Println("String 2: ", mystring2)
    }
    

    输出:

    String 1:  Geeks
    String 2:  Geeks
    
  • 如何找到字符串的长度:在Golang字符串,你可以找到使用两个功能之一是len(),另一种字符串的长度为RuneCountInString()。 RuneCountInString()函数由 UTF-8 包提供,该函数返回字符串出现的符文总数。 len()函数返回字符串的字节数。

    例子:

    // Go program to illustrate how to
    // find the length of the string
      
    package main
      
    import (
        "fmt"
        "unicode/utf8"
    )
      
    // Main function
    func main() {
      
        // Creating and initializing a string
        // using shorthand declaration
        mystr := "Welcome to GeeksforGeeks ??????"
      
        // Finding the length of the string
        // Using len() function
        length1 := len(mystr)
      
        // Using RuneCountInString() function
        length2 := utf8.RuneCountInString(mystr)
      
        // Displaying the length of the string
        fmt.Println("string:", mystr)
        fmt.Println("Length 1:", length1)
        fmt.Println("Length 2:", length2)
      
    }
    

    输出:

    string: Welcome to GeeksforGeeks ??????
    Length 1: 31
    Length 2: 31