Go語言程式將字串插入另一個字串


在 Go 程式語言中,字串是一種內建資料型別,用於表示字元序列。它們使用雙引號 (") 定義,可以包含任何有效的字元。當字串“插入”到另一個字串中時,它會被新增到更大的字串中或放置在更大的字串內。這可以透過替換更大字串中的特定子字串或在更大字串中的特定位置或索引處來完成。這在程式設計中經常使用,當需要以特定方式修改或更改字串時,例如透過新增字首或字尾或替換特定字元或子字串。

方法 1:使用切片方法

在這種方法中,為了將新字串插入到指定位置的原始字串中,此程式使用字串切片。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)包在程式中,其中 main 生成可執行示例,而 fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 建立一個 main 函式,並在該函式中宣告並初始化起始字串、新字串以及應插入新字串的位置。

  • 步驟 3 − 使用字串切片連線以下字串以建立一個新字串:原始字串的一部分,從開始到指定位置,以及從指定位置到結尾的原始字串的一部分。

  • 步驟 4 − 使用 fmt.Println() 函式在控制檯上列印連線的字串,其中 ln 表示換行符。

  • 步驟 5 − 在此示例中,“Hello, developer!”是原始字串,“software”是要插入的字串,位置 7 是它必須去的位置。軟體首先連線要插入的字串並從 0 到 7 切片原始字串;然後它從 7 切片到原始字串的末尾並連線所有內容。

示例

在此示例中,我們將學習如何使用切片將字串插入另一個字串。

package main
import (
   "fmt"
)

//create a function main to execute the program
func main() {
   initial_input := "Hello, developer!"  //create an original input string
   fmt.Println("The initial string given here is:", initial_input)
   new_input := "software"  //create a new string which is to be concatenated
   pos := 7
   fmt.Println("The string after new input is added:")
   fmt.Println(initial_input[:pos] + new_input + initial_input[pos:]) //concatenate the strings and print on the console
}

輸出

The initial string given here is: Hello, developer!
The string after new input is added:
Hello, softwaredeveloper!

方法 2:使用 bytes.Buffer 包

此程式使用 bytes.Buffer 包來建立一個新的緩衝區,寫入要插入的字串、從指定位置到結尾的原始字串切片以及直到指定位置的原始字串切片。使用緩衝區的 .String() 方法,生成所需的結果。讓我們看看示例和演算法以瞭解概念。

語法

buffer.String()

String() 方法是一種基於位元組的方法。在 Go 中,可增長的位元組緩衝區由緩衝區結構表示。String() 方法將緩衝區的內容作為字串返回。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)包在程式中,其中 main 生成可執行示例,而 fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 建立一個 main 函式,並在該函式中宣告並初始化起始字串、新字串以及應插入新字串的位置。

  • 步驟 3 − 利用位元組建立一個新的緩衝區。

  • 步驟 4 − 使用緩衝區的 WriteString() 方法將以下字串新增到緩衝區:原始字串的一部分,從開始到指定位置,以及從指定位置到結尾的原始字串的一部分。

  • 步驟 5 − 要獲取包含插入字串的完成字串,請使用緩衝區的 String() 方法。

  • 步驟 6 − 使用 fmt.Println() 函式釋出完成的字串,其中 ln 表示換行符。

示例

在此示例中,我們將學習如何使用緩衝區包將字串插入另一個切片。

package main
import (
   "bytes"
   "fmt"
)
//create a function main to execute the program
func main() {
   initial_input := "Hello, developer!"    //create an original string
   fmt.Println("The original string given here is:", initial_input)
   new_input := "software"  //create a new string 
   fmt.Println("The new string to be added here is:", new_input)
   pos := 7

   var buffer bytes.Buffer
   buffer.WriteString(initial_input[:pos])  //add the string to the buffer 
   buffer.WriteString(new_input)
   buffer.WriteString(initial_input[pos:])
   fmt.Println(buffer.String())    //print the concatenated string on the console
}

輸出

The original string given here is: Hello, developer!
The new string to be added here is: software
Hello, softwaredeveloper!

結論

我們使用兩個不同的示例執行了將字串插入另一個字串的程式。在第一個示例中,我們使用了字串切片,在第二個示例中,我們使用了 bytes.Buffer 包。兩個程式都給出類似的輸出。

更新於: 2023年2月20日

1K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告