How do you encode unicode code points in Go? In the example below I'm storing the hex representation of the unicode for ace of spades as \u1F0A1 but when I print it comes out as Ἂ1. Why is that? If I copy and paste the ace of spades glyph it prints fine.
package main
import "fmt"
func main() {
fmt.Println("🂡 \u1F0A1")
}
Output
🂡 Ἂ1
Example above in the Go playground https://play.golang.org/p/ukK57CnVuE
Lowercase \u is for Unicode code points from \u0000 to \uFFFF. Use \U if you want to have code points above 0xFFFF:
package main
import "fmt"
func main() {
fmt.Println("🂡 = \U0001F0A1")
}
See also: playground and the string literals section of the specification.
Related
I am following Dan Gookin's Guide to ncurses at the same time as I attempt to adapt the code into swift. First I noticed that printw is unavailable as C modules cannot import variadic functions, but this can be easily avoided using addstr.
Now the second problem, which leads to this question, is that I am not finding a way of passing the contents of a variable to addstr if the contents of the variable were created using getstr, so please consider the following:
import Foundation
import CNCURSES // marathon: https://github.com/lf-araujo/Cncurses.git
import Glibc
initscr()
var first = [Int8]()
getstr(&first)
addstr("What is your last name? ")
refresh()
var last = [Int8]()
getstr(&last)
addstr("Pleased to meet you, \(first) \(last)!")
refresh()
getch()
endwin()
exit(0)
If I enter John Smith as my name, the result of the above is two empty brackets [] [].
How do I pass the contents of first and last to addstr in this particular case?
I'm not able to solve my problem with writing special characters ěščřžýáíé using method write(int b) from OutputStream class. I'm using this class to redirect console output to JTextArea.
class CustomOutputStream extends OutputStream {
private JTextArea textArea;
CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
#Override
public void write(int b) {
textArea.append(String.valueOf((char) b));
// scrolls the text area to the end of data
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
It works fine for standard characters. For characters ěščřžýáíé it prints unreadable characters.
I don't know how to set character encoding or how to solve this by other way.
Thank you, J.
You convert b which was an int to char type, so you lose most of the information. And you are not interpreting the b as unicode code point.
textArea.append(Character.toChars(b))
If your original text is not Unicode, you may decode it.
In Perl if I had trailing blanks in a string, I would use this code
$line =~ s/ +$//;
Is there a similar command or function in swift?
Swift provides no support for regular expressions. It doesn't need to, though, because the only place you'll ever use Swift is in the presence of Cocoa — and Cocoa's Foundation framework does provide support for regular expressions (and has other string-handling commands). Swift String and Framework's NSString are bridged to one another.
Thus, you could use stringByReplacingOccurrencesOfString:withString:options:range: with a regular expression pattern, for example (assuming that stringByTrimmingCharactersInSet: is too simple-minded for your purposes).
If you want to do this multiple times I suggest you add this handy extension to your project:
extension String {
var strip: String {
return self.trimmingCharacters(in: .whitespaces)
}
}
Now you can do something as simple as this:
let line = " \t BB-8 likes Rey \t "
line.strip // => "BB-8 likes Rey"
If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via Carthage then use it exactly like in the example above:
import HandySwift
let line = " BB-8 likes Rey "
line.strip // => "BB-8 likes Rey"
I am using mongoimport to import a json file. In one of the fields there is potentially regex expressions that contain hex strings such as:
{ "field1" : "/\x01\x02\x03/" }
I am getting the following error "FailedToParse: Hex escape not supported"
Try using double escape, what you have fails JSON validation.
{ "field1": "/\\x01\\x02\\x03/" }
This passes validation at http://jsonlint.com/
You may have to create a special case in your code for setting and getting this value, there is also an escape notion of \u in JSON which I believe denotes a hex escape but I've never used it before.
From some research I found this handy bit of info and example.
// Store RegExp pattern as a string
// Double backslashes are required to put literal \ characters in the string
var jsonObject = { "regex": "^http:\\/\\/" };
I am trying to capture user input in Go with little luck. I can get non-spaced words to work:
var s string
println("enter string:")
fmt.Scan(&s)
However, the Go documentation says that scan will delimit at spaces and new lines. So I think I have to set up bufio.Reader's ReadLine. Here is my attempt, which will not compile:
package main
import (
"bufio"
"os"
"fmt"
)
const delim = '\n'
const file = "file"
func main() {
r := bufio.NewReader() *Reader
println("enter string:")
line, err := r.ReadString(delim)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(line)
}
errors:
1.go:14: not enough arguments in call to bufio.NewReader
1.go:14: undefined: Reader
So, how do I define "Reader"? And if it was defined, would this be the correct way to capture the input as a string, delimited at "\n", and not at the space? Or should I be doing something completely different?
Thanks in advance.
Change
r := bufio.NewReader() *Reader
to read
r := bufio.NewReader(os.Stdin)
to fix the problem.
The original encantation is incorrect because you seem to just copied and pasted the method's signature from the spec, but the spec defines the signature, not an example of a call, so *Reader in there is the method's return type (the type your variable r will have). And the method's sole argument is defined to be rd io.Reader; that interface is conveniently implemented by the os.Stdin symbol which seems like a perfect match for your task.
P.S.
Consider reading all the docs in the "Learning Go" documentation section, especially "Effective Go".
If you look at the documentation for bufio.NewReader, it takes an argument of type io.Reader (which makes sense, because it takes a normal reader and makes it buffered, similar to java.io.BufferedReader in Java, which also takes a Reader argument). What is io.Reader? Looking at its documentation, it is an interface, specifying anything that has a Read method. Many types have a Read method; most commonly, *os.File. So you can construct a File using os.Open etc.
f, _ := os.Open(file)
r := bufio.NewReader(f)