如何在 Golang 中連線兩個字串?


在 Golang 中連線兩個字串的最簡單方法是使用“+”運算子。例如,

示例 1

package main
import (
   "fmt"
)
func main() {
   str1 := "Hello..."
   str2 := "How are you doing?"
   
   fmt.Println("1st String:", str1)
   fmt.Println("2nd String:", str2)

   // Concatenate using the + Operator
   fmt.Println("Concatenated String:", str1 + str2)
}

輸出

將產生以下輸出

1st String: Hello...
2nd String: How are you doing?
Concatenated String: Hello...How are you doing?

使用 strings.Join() 連線

strings.Join() 是 Golang 中內建的一個函式,用於將多個字串連線成一個字串。

語法

其語法如下:

func Join(stringSlice []string, sep string) string

其中:

  • stringSlice – 要連線的字串。
  • sep – 要放在切片元素之間的分隔字串。

示例 2

讓我們考慮以下示例:

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   m := []string{"IndexByte", "String", "Function"}
   n := []string{"Golang", "IndexByte", "String", "Package"}

   // Display the Strings
   fmt.Println("Set 1 - Slices of Strings:", m)
   fmt.Println("Set 2 - Slices of Strings:", n)

   // Using the Join Function
   output1 := strings.Join(m, "-")
   output2 := strings.Join(m, "/")
   output3 := strings.Join(n, "*")
   output4 := strings.Join(n, "$")

   // Display the Join Output
   fmt.Println("\n Joining the slices of Set 1 with '-' delimiter: \n", output1)
   fmt.Println("\n Joining the slices of Set 1 with '/' delimiter: \n", output2)
   fmt.Println("\n Joining the slices of Set 2 with '*' delimiter: \n", output3)
   fmt.Println("\n Joining the slices of Set 2 with '$' delimiter: \n", output4)
}

輸出

它將生成以下輸出:

Set 1 - Slices of Strings: [IndexByte String Function]
Set 2 - Slices of Strings: [Golang IndexByte String Package]

   Joining the slices of Set 1 with '-' delimiter:
   IndexByte-String-Function

   Joining the slices of Set 1 with '/' delimiter:
   IndexByte/String/Function

   Joining the slices of Set 2 with '*' delimiter:
   Golang*IndexByte*String*Package

   Joining the slices of Set 2 with '$' delimiter:
   Golang$IndexByte$String$Package

示例 3

我們再來看一個示例。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Defining the Variables
   var s []string
   var substr string
   var substr1 string
   var result string
   var output string

   // Intializing the Strings
   s = []string{"This", "is", "String", "Function"}
   substr = "..."
   substr1 = " "

   // Display the input slice of strings
   fmt.Println("Input Slice of Strings:", s)

   // Using the Join Function
   result = strings.Join(s, substr)
   output = strings.Join(s, substr1)

   // Displaying output of Join function
   fmt.Println("Joining with '...' delimiter:", result)
   fmt.Println("Joining with ' ' delimiter:", output)
}

輸出

它將生成以下輸出:

Input Slice of Strings: [This is String Function]
Joining with '...' delimiter: This...is...String...Function
Joining with ' ' delimiter: This is String Function

更新於:2022 年 3 月 10 日

1000+ 次瀏覽

職業生涯從這裡開始

完成本課程以獲得認證

開始學習
廣告