Go語言程式演示如何在字串中寫入雙引號
在 Go 語言中,有多種技術可以列印帶雙引號的字串。在本文中,我們將學習這些技術以及各種示例。
語法
func Quote(s string) string
Quote() 函式位於 strconv 包中,用於在給定字串文字中新增雙引號。該函式接受要加引號的字串變數作為引數,並在新增雙引號後返回字串。
func Sprintf(format string, a ...interface{}) string
此函式返回格式化的字串。它採用多個字串格式的引數。第一個引數應為字串格式,後跟可變數量的引數。
func Join(s []string, sep string) string
join 函式用於將陣列轉換為字串。此函式位於 strings 包中。它接受兩個引數,第一個是要轉換的陣列,第二個是將陣列元素轉換為字串後應使用的分隔符,並返回最終字串。
演算法
步驟 1 - 首先,我們需要匯入 fmt 包。
步驟 2 - 開始 main() 函式。
步驟 3 - 在 main() 函式內部,初始化一個字串型別的變數併為其賦值。
步驟 4 - 然後將變數列印到螢幕上。
步驟 5 - 為了在雙引號中包含此字串,請使用 printf() 函式
示例 1
在這個例子中,我們將使用 printf() 以及 %q 格式化動詞函式來列印帶雙引號的字串。
package main import "fmt" func main() { var str string= "You must be the change you wish to see in the world." fmt.Println("The given string is:\n", str) fmt.Println() fmt.Printf("Printing the above string in double quotes as:") fmt.Println() fmt.Printf("%q\n", str) }
輸出
The given string is: You must be the change you wish to see in the world. Printing the above string in double quotes as: "You must be the change you wish to see in the world."
示例 2
在這個例子中,我們將編寫一個 Go 語言程式,演示如何使用 strconv 包中的 Quote() 函式在字串中寫入雙引號。
package main import ( "fmt" "strconv" ) func main() { var str string = "Never give up" fmt.Println("The given string is:\n", str) fmt.Println() var result string = strconv.Quote(str) fmt.Println("Printing the above string in double quotes as:\n", result) fmt.Println() }
輸出
The given string is: Never give up Printing the above string in double quotes as: "Never give up"
示例 3
在這個例子中,我們將編寫一個 Go 語言程式,演示如何使用反引號在字串中寫入雙引號。使用反引號是另一種常用的方法,用於列印帶引號的字串。
package main import ( "fmt" ) func main() { var str string = `This is a string with "double quotes" inside` fmt.Println("The given string is:\n", str) }
輸出
The given string is: This is a string with "double quotes" inside
示例 4
在本文中,我們將編寫一個 Go 語言程式,演示如何使用 sprint() 函式在字串中寫入雙引號。
package main import ( "fmt" ) func main() { var str string = "Prevention is better than cure" fmt.Println("The given string is:\n", str) fmt.Println() var result string = fmt.Sprintf("%s", str) fmt.Println("The final string obtained after placing it to quotations is:\n", result) }
輸出
The given string is: Prevention is better than cure The final string obtained after placing it to quotations is: "Prevention is better than cure"
示例 5
在本文中,我們將編寫一個 Go 語言程式,演示如何使用 join() 函式在字串中寫入雙引號。
package main import ( "fmt" "strings" ) func main() { var str string = "The way to get started is to quit talking and begin doing." fmt.Println("The given string is:\n", str) fmt.Println() var result string = strings.Join([]string{""", str, """}, "") fmt.Println("The final string obtained after placing it to quotations is:\n", result) }
輸出
The given string is: The way to get started is to quit talking and begin doing. The final string obtained after placing it to quotations is: "The way to get started is to quit talking and begin doing."
結論
我們已經成功編譯並執行了一個 Go 語言程式,用於演示如何在字串中寫入雙引號以及示例。我們在這個程式中使用了不同的函式,包括 sprint()、quote()、Join() 等,以便將給定的字串文字包含在引號中。