Go語言程式:用特定字元替換字串中的空格


在 Go 程式語言中,字串是一種內建資料型別,用於表示字元序列。它們使用雙引號 (") 定義,可以包含任何有效的 Unicode 字元。這裡首先使用的是 Replace() 方法,它用特定字元替換空格,還可以應用許多其他方法來解決這個問題。修改後的字串將使用 fmt 包列印到控制檯。

方法 1:使用 strings.Replace() 函式

在此方法中,空格字元 (" ") 使用 Replace() 函式替換為字元 "-"。該函式被指示替換所有出現的情況,最終輸入為 "-1"。如果您只想替換特定數量的出現,則可以輸入特定數字。

語法

strings.Replace()

Go 語言中的 Replace() 函式用於將字串中特定子字串的所有例項替換為另一個子字串。該函式需要三個輸入:原始字串、要更改的子字串和替換子字串。它返回一個應用了所需替換的新字串。

演算法

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

  • 步驟 2 - 建立一個 initial_string,其空格將被特定字元替換。

  • 步驟 3 - 使用 Go 語言中的 print 語句在控制檯列印字串。

  • 步驟 4 - 使用 strings.Replace() 函式將空格替換為新字元。

  • 步驟 5 - 使用 fmt.Println() 函式(其中 ln 表示換行)在控制檯列印修改後的字串。

示例

在下面的示例中,我們將使用名為 string.Replace() 的內部字串函式來用特定字元替換字串中的空格。

package main
import (
   "fmt"
   "strings"    //import fmt and strings package
)

//create main function to execute the program
func main() {
   initial_string := "Hello alexa!"  //create string
   fmt.Println("The initial string created here is:", initial_string)
   replaced_string := strings.Replace(initial_string, " ", "-", -1)  //replace the space in string    using Replace() function
   fmt.Println("The replaced string after using replace method:")
   fmt.Println(replaced_string) //print the modified string on the console
}

輸出

The initial string created here is: Hello alexa!
The replaced string after using replace method:
Hello-alexa!

方法 2:使用 for 迴圈

在這個示例中,我們將學習如何用特定字元替換字串中的空格。這裡,這種方法使用 for 迴圈遍歷原始字串中的每個字元,檢查當前字元是否為空格。如果是,則將替換字元新增到目標字串中。如果不是,則按原樣將字元新增到修改後的字串中。執行此程式將產生與前面示例相同的結果,即短語“Hello-alexa!”。

演算法

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

  • 步驟 2 - 建立一個 main 函式,並在該函式中建立一個變數來儲存要更改的起始字串。

  • 步驟 3 - 建立一個空字串變數並初始化它以儲存更新後的字串。

  • 步驟 4 - 再次遍歷起始字串中的每個字元。

  • 步驟 5 - 如果當前字元為空格,則將指定的替換字元新增到修改後的字串中。

  • 步驟 6 - 如果當前字元不是空格,則將字元新增到修改後的字串中。

  • 步驟 7 - 直到處理完所有字元,才迭代原始字串。修改後的字串現在包含原始字串,其中空格已被請求的字元替換。

  • 步驟 8 - 使用 fmt.Println() 函式(其中 ln 表示換行)在控制檯列印修改後的字串。

示例

在下面的示例中,我們將使用使用者定義的函式在 Go 語言中用特定字元替換字串中的空格。

package main
import (
   "fmt"   //import fmt package in the program
)

//create main function to execute the program
func main() {
   initial_string := "Hello alexa!"  //create a string
   fmt.Println("The initial string created here is:", initial_string)
   var replaced_string string
   for _, ch := range initial_string {
      if ch == ' ' {
         replaced_string += "-"  //if the character is empty replace it with the specified character
      } else {
         replaced_string += string(ch) //else use the same character
      }
   }
   fmt.Println("The replaced string given here is:")
   fmt.Println(replaced_string) //print the modified string using print statement in Golang
}

輸出

The initial string created here is: Hello alexa!
The replaced string given here is:
Hello-alexa!

結論

我們執行了用特定字元替換字串中空格的程式,使用了兩個示例。在第一個示例中,我們使用了內建的 Replace() 函式,而在第二個示例中,我們使用了 for 迴圈來執行程式。

更新於:2023年2月20日

1K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告