-3

I tried with the following code but getting the same string in result:

package main

import (
    "fmt"
    "strings"
)

func main() {
    var s = "\b\x02\b\x02\r\n"
    a := fmt.Sprintf("%q", s)
    fmt.Println("a:", a)
    b := strings.TrimRight(a, "\r\n")
    fmt.Println("b:", b)
}
Jeet
  • 75
  • 1
  • 12
  • [possible duplicate question here](https://stackoverflow.com/questions/44448384/how-remove-n-from-lines-from-golang) – nagleria Jan 23 '19 at 13:58

1 Answers1

6

strings.TrimRight() works just fine. The "problem" in your case is that the string value stored in the a variable does not end with "\r\n".

The reason for that is because you "quote" it using fmt.Sprintf(), and the string will end with "\\r\\n", and additionally even a double quotation mark will be added to it (that is, it ends with a backslash, the letter r, another backslash, the letter n and a double quote character).

If you don't quote your string, then:

var s = "\b\x02\b\x02\r\n"
fmt.Printf("s: %q\n", s)
b := strings.TrimRight(s, "\r\n")
fmt.Printf("b: %q\n", b)

Output (try it on the Go Playground):

s: "\b\x02\b\x02\r\n"
b: "\b\x02\b\x02"
icza
  • 389,944
  • 63
  • 907
  • 827
  • 2
    Just a small note, using `%q` it actually ends with `\r\n"` because it also wraps the input string in quote characters. – Adrian Jan 23 '19 at 14:29