在Go中用双引号创建或打印字符串的4种方法

1,976 阅读3分钟

要在Go中打印或创建一个带有双引号的字符串,可以使用以下任何一种方法。

请看下面的例子,了解这些方法的工作原理。

使用%q 格式化动词打印一个带双引号的字符串

创建带双引号的字符串的最简单方法是使用 fmt.Printf()fmt.Sprintf()函数和%q format动词,它就是用来做这个的。来自fmt 包的文档。

%q a double-quoted string safely escaped with Go syntax

例子

package main
import "fmt"
func main() {
str := "Hello https://gosamples.dev"
// print string with double quotes
 fmt.Printf("%q\n", str)
// create string with double quotes
 quoted := fmt.Sprintf("%q", str)
fmt.Println(quoted)
}

使用带转义双引号的格式打印一个带双引号的字符串

另外,要打印或创建一个带双引号的字符串,你可以手动添加这些引号,在格式的 fmt.Printf()fmt.Sprintf()函数的格式中手动添加这些引号。注意,字符串中的引号必须通过在引号前添加一个反斜杠字符来转义:\"

例子

package main
import "fmt"
func main() {
str := "Hello https://gosamples.dev"
// print string with double quotes
 fmt.Printf("\"%s\"\n", str)
// create string with double quotes
 quoted := fmt.Sprintf("\"%s\"", str)
fmt.Println(quoted)
}

使用函数创建带有双引号的字符串 strconv.Quote()函数创建一个带有双引号的字符串

也可以使用函数 strconv.Quote()来创建一个带有双引号的新字符串。在这种情况下,打印和创建看起来几乎一样,因为你需要先创建带引号的字符串,然后就可以打印或在应用程序中使用它。

例子

package main
import (
"fmt"
"strconv"
)
func main() {
str := "Hello https://gosamples.dev"
// print string with double quotes
 fmt.Println(strconv.Quote(str))
// create string with double quotes
 quoted := strconv.Quote(str)
fmt.Println(quoted)
}

使用反引号(原始字符串)格式打印一个带双引号的字符串

创建或打印带双引号的字符串的最后一种最人性化的方法是使用原始字符串字面的格式为 fmt.Printf()fmt.Sprintf()函数的格式。原始字符串字面意义是反引号之间的任何字符序列,如`abc` 。反引号之间的字符串会被打印出来,它们可能包含换行符,并且不解释转义字符。

所以在我们的例子中,我们不必像第二个例子那样使用转义的双引号字符。唯一的问题是当我们想打印带换行的引号字符串时。请看下面的例子。由于我们打印的是原始字符串,我们必须使用Enter ,以添加换行符,这使得代码看起来很丑。出于这个原因,我们建议使用第二种方法,将双引号转义。

例子

package main
import "fmt"
func main() {
str := "Hello https://gosamples.dev"
// print string with double quotes
 fmt.Printf(`"%s"
`, str)
// create string with double quotes
 quoted := fmt.Sprintf(`"%s"`, str)
fmt.Println(quoted)
}

所有的例子都返回相同的输出😉:

"Hello https://gosamples.dev"
"Hello https://gosamples.dev"