Go - 字串



Go 程式設計中廣泛使用的字串是隻讀的位元組序列。在 Go 程式語言中,字串是切片。Go 平臺提供了各種操縱字串的庫。

  • unicode
  • regexp
  • strings

建立字串

建立字串的最直接的方法是編寫 −

var greeting = "Hello world!"

每當在您的程式碼中遇到字串文字時,編譯器都會建立一個字串物件及其值(在本例中,“Hello world!')。

字串字面值包含稱為符文的有效的 UTF-8 序列。字串包含任意位元組。

package main

import "fmt"

func main() {
   var greeting =  "Hello world!"
   
   fmt.Printf("normal string: ")
   fmt.Printf("%s", greeting)
   fmt.Printf("\n")
   fmt.Printf("hex bytes: ")
   
   for i := 0; i < len(greeting); i++ {
       fmt.Printf("%x ", greeting[i])
   }
   
   fmt.Printf("\n")
   const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98" 
   
   /*q flag escapes unprintable characters, with + flag it escapses non-ascii 
   characters as well to make output unambigous */
   fmt.Printf("quoted string: ")
   fmt.Printf("%+q", sampleText)
   fmt.Printf("\n")  
}

這將產生以下結果 −

normal string: Hello world!
hex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 
quoted string: "\xbd\xb2=\xbc \u2318"

注意 − 字串字面值是不可變的,因此一旦建立了字串字面值,就無法更改它。

字串長度

len(str) 方法返回字串字面值中包含的位元組數。

package main

import "fmt"

func main() {
   var greeting =  "Hello world!"
   
   fmt.Printf("String Length is: ")
   fmt.Println(len(greeting))  
}

這將產生以下結果 −

String Length is : 12

連線字串

strings 包含了一個連線多個字串的方法 join

strings.Join(sample, " ")

Join 將陣列的元素連線起來,建立一個字串。第二個引數 seperator 位於陣列元素之間。

我們來看一下以下示例 −

package main

import ("fmt" "math" )"fmt" "strings")

func main() {
   greetings :=  []string{"Hello","world!"}   
   fmt.Println(strings.Join(greetings, " "))
}

這將產生以下結果 −

Hello world!
廣告
© . All rights reserved.