how to remove trailing "\r\n" from string - string

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)
}

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"

Related

Converting unicode to "java

I have this a problem with character conversion. It all starts with this string: U+1F618. According to fileformat.info, this string is now (almost) in the HTML Entity (hex) notation.
But I need this character to be converted into a C/C++/Java source code-notation. I really don't know if this is the official name for the notation, but I assume this site to be correct :).
So basically my question is, instead of outputting to the real emoji, how can I get the value \uD83D\uDE18?
package main
import (
"fmt"
"html"
"strconv"
"strings"
)
func main() {
original := "\\U0001f618"
// Hex String
h := strings.ReplaceAll(original, "\\U", "0x")
// Hex to Int
i, _ := strconv.ParseInt(h, 0, 64)
// Unescape the string (HTML Entity -> String).
str := html.UnescapeString(string(i))
// Display the emoji.
fmt.Println(str)
// but I want something like this: \uD83D\uDE18
}
If you have the input as a string, e.g.
s := "\\U0001f618"
You may use strconv.Unquote() to unquote it. Be sure the string you pass to it is quoted (it must be wrapped with backticks or double quotes):
s2, err := strconv.Unquote(`"` + s + `"`)
fmt.Println(s2, err)
This will give you an s2 string that contains your emoji:
😘 <nil>
Java's string model is a char[] which contains the UTF-16 code points. Go's memory model of string is the UTF-8 encoded byte sequence.
To convert a Go string to UTF-16, you may use the unicode/utf16 package of the standard lib. For example utf16.Encode() encodes a series of runes (unicode codepoints) to UTF-16. You get a series of runes from a Go string with a simple type conversion: []rune("some string").
u16 := utf16.Encode([]rune(s2))
fmt.Printf("%X\n", u16)
The above prints the UTF16 codepoints in hexadecimal format:
[D83D DE18]
To get the format you want, use this loop:
buf := &strings.Builder{}
for _, v := range u16 {
fmt.Fprintf(buf, "\\u%X", v)
}
fmt.Println(buf.String())
Which outputs:
\uD83D\uDE18
Try the examples on the Go Playground.
You can capture this series of conversions in a function:
func convert(s string) (string, error) {
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
return "", err
}
buf := &strings.Builder{}
for _, v := range utf16.Encode([]rune(s2)) {
fmt.Fprintf(buf, "\\u%X", v)
}
return buf.String(), nil
}
Using it:
fmt.Println(convert("\\U0001f618"))
Which outputs (try it on the Go Playground):
\uD83D\uDE18 <nil>

How can I remove the last 4 characters from a string?

I want to remove the last 4 characters from a string, so "test.txt" becomes "test".
package main
import (
"fmt"
"strings"
)
func main() {
file := "test.txt"
fmt.Print(strings.TrimSuffix(file, "."))
}
This will safely remove any dot-extension - and will be tolerant if no extension is found:
func removeExtension(fpath string) string {
ext := filepath.Ext(fpath)
return strings.TrimSuffix(fpath, ext)
}
Playground example.
Table tests:
/www/main.js -> '/www/main'
/tmp/test.txt -> '/tmp/test'
/tmp/test2.text -> '/tmp/test2'
/tmp/test3.verylongext -> '/tmp/test3'
/user/bob.smith/has.many.dots.exe -> '/user/bob.smith/has.many.dots'
/tmp/zeroext. -> '/tmp/zeroext'
/tmp/noext -> '/tmp/noext'
-> ''
Though there is already an accepted answer, I want to share some slice tricks for string manipulation.
Remove last n characters from a string
As the title says, remove the last 4 characters from a string, it is very common usage of slices, ie,
file := "test.txt"
fmt.Println(file[:len(file)-4]) // you can replace 4 with any n
Output:
test
Playground example.
Remove file extensions:
From your problem description, it looks like you are trying to trim the file extension suffix (ie, .txt) from the string.
For this, I would prefer #colminator's answer from above, which is
file := "test.txt"
fmt.Println(strings.TrimSuffix(file, filepath.Ext(file)))
You can use this to remove everything after last "."
go playground
package main
import (
"fmt"
"strings"
)
func main() {
sampleInput := []string{
"/www/main.js",
"/tmp/test.txt",
"/tmp/test2.text",
"/tmp/test3.verylongext",
"/user/bob.smith/has.many.dots.exe",
"/tmp/zeroext.",
"/tmp/noext",
"",
"tldr",
}
for _, str := range sampleInput {
fmt.Println(removeExtn(str))
}
}
func removeExtn(input string) string {
if len(input) > 0 {
if i := strings.LastIndex(input, "."); i > 0 {
input = input[:i]
}
}
return input
}

How create string with escape character?

I want to create string \"str\" but i want to give variable name to str.
For ex :
x := "name"
q := fmt.Sprintf("\"%s\"", x)
I want 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

Convert hex to alphabet

How do I obtain the alphabet value from the hex value in Go?
package main
import (
"encoding/hex"
"fmt"
)
func main() {
a := []byte{0x61}
c := hex.Dump(a)
fmt.Println(c,a)
}
http://play.golang.org/p/7iAs2kKw5v
You could use a fmt.Printf() format (example):
func main() {
a := []byte{0x61}
c := hex.Dump(a)
fmt.Printf("'%+v' -- '%s'\n", c, a)
}
Output:
'00000000 61 |a|
' -- 'a'
The %s format is enough to convert the 0x61 in 'a'.
Your question is a little misleading.
Based on your question what you really want is convert a byte value or a []byte (byte slice) to a string or character (which is more or less a rune in Go).
Henceforth I will separate the single byte value from the []byte using these variables:
b := byte(0x61)
bs := []byte{b}
To convert it to a string, you can simply use a conversion which is the cleanest and most simple:
s := string(bs)
If you want it as a "character", you can convert it to a rune:
r := rune(b)
Another solution is using fmt.Printf() as mentioned in VonC's answer and using the %s verb which is:
%s the uninterpreted bytes of the string or slice
You might want to take a look at these alternatives:
%c the character represented by the corresponding Unicode code point
%q a single-quoted character literal safely escaped with Go syntax.
%q accepts both a byte, []byte and rune.
See this litte example to demonstrate these (try it on the Go Playground):
b := byte(0x61)
bs := []byte{b}
fmt.Printf("%s\n", bs)
fmt.Printf("%c\n", b)
fmt.Println(string(bs))
fmt.Printf("%q\n", bs)
fmt.Printf("%q\n", b)
fmt.Printf("%q\n", rune(b))
Output:
a
a
a
"a"
'a'
'a'
If you need the result as a string, you can use the fmt.Sprintf() variant mentioned in satran's answer like this:
s := fmt.Sprintf("%s", bs)
But it's easier to just use the string conversion (string(bs)).
If you just want the string you can you fmt.Sprintf.
package main
import (
"fmt"
)
func main() {
a := []byte{0x61}
c := fmt.Sprintf("%s", a)
fmt.Println(c)
}

Strange CSV result for quoted strings in go encoding/csv

I have this little bit of code that kept me busy the whole weekend.
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
f, err := os.Create("./test.csv")
if err != nil {
log.Fatal("Error: %s", err)
}
defer f.Close()
w := csv.NewWriter(f)
var record []string
record = append(record, "Unquoted string")
s := "Cr#zy text with , and \\ and \" etc"
record = append(record, s)
fmt.Println(record)
w.Write(record)
record = make([]string, 0)
record = append(record, "Quoted string")
s = fmt.Sprintf("%q", s)
record = append(record, s)
fmt.Println(record)
w.Write(record)
w.Flush()
}
When run it prints out:
[Unquoted string Cr#zy text with , and \ and " etc]
[Quoted string "Cr#zy text with , and \\ and \" etc"]
The second, quoted text is exactly what I would wish to see in the CSV, but instead I get this:
Unquoted string,"Cr#zy text with , and \ and "" etc"
Quoted string,"""Cr#zy text with , and \\ and \"" etc"""
Where do those extra quotes come from and how do I avoid them?
I have tried a number of things, including using strings.Quote and some such but I can't seem to find a perfect solution. Help, please?
It's part of the standard for storing data as CSV.
Double quote characters need to be escaped for parsing reasons.
A (double) quote character in a field must be represented by two (double) quote characters.
From: http://en.wikipedia.org/wiki/Comma-separated_values
You don't really have to worry because the CSV reader un-escapes the double quote.
Example:
package main
import (
"encoding/csv"
"fmt"
"os"
)
func checkError(e error){
if e != nil {
panic(e)
}
}
func writeCSV(){
fmt.Println("Writing csv")
f, err := os.Create("./test.csv")
checkError(err)
defer f.Close()
w := csv.NewWriter(f)
s := "Cr#zy text with , and \\ and \" etc"
record := []string{
"Unquoted string",
s,
}
fmt.Println(record)
w.Write(record)
record = []string{
"Quoted string",
fmt.Sprintf("%q",s),
}
fmt.Println(record)
w.Write(record)
w.Flush()
}
func readCSV(){
fmt.Println("Reading csv")
file, err := os.Open("./test.csv")
defer file.Close();
cr := csv.NewReader(file)
records, err := cr.ReadAll()
checkError(err)
for _, record := range records {
fmt.Println(record)
}
}
func main() {
writeCSV()
readCSV()
}
Output
Writing csv
[Unquoted string Cr#zy text with , and \ and " etc]
[Quoted string "Cr#zy text with , and \\ and \" etc"]
Reading csv
[Unquoted string Cr#zy text with , and \ and " etc]
[Quoted string "Cr#zy text with , and \\ and \" etc"]
Here's the code for the write function.
func (w *Writer) Write(record []string) (err error)
I have csv file with line with double quote string like:
text;//*[#class="price"]/span;text
And csv Reader generate error to read csv file.
Helpful was:
reader := csv.NewReader(file)
reader.LazyQuotes = true
The s variable's value is not what you think it is. http://play.golang.org/p/vAEYkINWnm

Resources