简体   繁体   中英

Golang trimPrefix from string "\"

I've seen that golang have the function func TrimPrefix(s, prefix string) string which returns s without the provided leading prefix string.

My problem is that I have a string which start with the character "\\" (for example "\\foo"). When I try to use TrimPrefix I getting an error.

golang code:

var s = "\foo"
    s = strings.TrimPrefix(s, "\")
    fmt.Print(s)

error:

./prog.go:10:32: newline in string
./prog.go:10:32: syntax error: unexpected newline, expecting comma or )

I have seen that it is due to golang understang "\\" as the scape character. Do you know if ther is any golang option I can use in order to make golang understand that I don't want to use "\\" as the escape character?

"\\" is not a valid Go string literal. What you get is a compile-time error. In interpreted string literals backslash \\ is a special character.

If you want the string to contain a backslash character, you have to use the sequence \\\\ :

var s = "\\foo"
s = strings.TrimPrefix(s, "\\")

Which will output (try it on the Go Playground ):

foo

Another option is to use raw string literals where the backslash is not special:

var s = `\foo`
s = strings.TrimPrefix(s, `\`)

Try this one on the Go Playground .

if you only want to trim the prefix which is a specific prefix( like "\\" is a prefix with length of 1 ), you can use slice function as : str[len(prefix):] .

Just because it is a prefix -- head of a string and a length-known prefix.

Ignore my post if you only want to know the use of TrimPrefix . :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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