简体   繁体   English

如何用转义符创建字符串?

[英]How create string with escape character?

I want to create string \\"str\\" but i want to give variable name to str. 我想创建字符串\\"str\\"但是我想给str指定变量名。 For ex : x := "name" q := fmt.Sprintf("\\"%s\\"", x) I want q = "\\"name\\"" 例如: x := "name" q := fmt.Sprintf("\\"%s\\"", x)我要q = "\\"name\\""

I tried this 我试过

Use escape sequences preceded by \\ to show literal special characters in a formatted string \\\\ for \\ and \\" for " 使用以\\开头的转义序列,可以在格式字符串\\\\\\ \\" ,而\\""

package main

import (
    "fmt"
)

func main() {
    x := "hello"
    q := fmt.Sprintf("\\\"%s\"\\", x)
    fmt.Println(q)
}

A more functional, flexible solution, depending on your taste: 一个更实用,更灵活的解决方案,具体取决于您的口味:

x := "hello"
p := []byte{'"', '\\', '"', '"'}
q := append(append(p, []byte(x)...), p...)
fmt.Printf("%s", q)

https://play.golang.org/p/MHOsdefZYW https://play.golang.org/p/MHOsdefZYW

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM