Converting Integer to String in url.Query().Set using String function [duplicate] - go

This question already has answers here:
How to convert an int value to string in Go?
(10 answers)
Closed last year.
this is my day 1 using goLang, I am currently trying to consume a data but I encounter an error, and that's converting integer to string
func createLink(title string, page int) string {
url := url.URL{
Scheme: "https",
Host: "jsonmock.hackerrank.com",
Path: "/api/movies/search/",
}
query := url.Query()
query.Set("page", string(page))
query.Set("title", title)
url.RawQuery = query.Encode()
return url.String()
}
you can try that code, and the result is
actual result :
https://jsonmock.hackerrank.com/api/movies/search/?page=%01&title=spiderman
expected result :
https://jsonmock.hackerrank.com/api/movies/search/?page=1&title=spiderman
There's %01 , an that's something that I do not want. i believe that I made a mistake in converting an integer to string

You should use strconv.Itoa() method to format your integers as strings. This is better explained in the linked answer. For the sake of completeness, here's how you end up with %01 in your result:
first, int 1 gets "plain-converted" to string by following this conversion rule:
Converting a signed or unsigned integer value to a string type yields
a string containing the UTF-8 representation of the integer. Values
outside the range of valid Unicode code points are converted to
"\uFFFD".
then the resulting string (with character of unicode code point equal to 1) gets URL-encoded, ending up with %01 as its representation.
As a sidenote, you're warned about this if you run go vet over your code:
hello.go:19:20: conversion from int to string yields a string of one
rune, not a string of digits (did you mean fmt.Sprint(x)?)
While this doesn't always give you absolutely the best advice on how to fix your error, it at least pushed you into the right direction. And it's strongly recommended to get used to the idea of running this (or similar) kind of checks from day 1 of learning language.

Related

Convert a string into ascii in Ada

I am trying to convert small strings into their respective ascii decimal values. Like converting the string "Ag" to "065103".
I tried using
integer_variable : Integer := Integer'Value(Ag);
but that gives me constraint error: bad input for 'Value: "Ag".
Is there something else I can use to make this work? Could I just use enumeration?
Strings in Ada are arrays of Characters, thus if you want to convert String to Integer values you have to do this for each Character separately, by taking its position in enumeration (as suggested in the comment to your question). In your example it could be:
integer_variable1 : Natural := Character'Pos('A');
integer_variable2 : Natural := Character'Pos('g');

Golang Typecasting

I have specific questions for my project
input = "3d6"
I want to convert this string some parts to integer. For instance I want to use input[0] like integer.
How can I do this?
There's two problems here:
How to convert a string to an integer
The most straightforward method is the Atoi (ASCII to integer) function in the strconv package., which will take a string of numeric characters and coerce them into an integer for you.
How to extract meaningful components of a known string pattern
In order to use strconv.Atoi, we need the numeric characters of the input by themselves. There's lots of ways to slice and dice a string.
You can just grab the first and last characters directly - input[:1] and input[2:] are the ticket.
You could split the string into two strings on the character "d". Look at the split method, a member of the strings package.
For more complex problems in this space, regular expressions are used. They're a way to define a pattern the computer can look for. For example, the regular expression ^x(\d+)$ will match on any string that starts with the character x and is followed by one or more numeric characters. It will provide direct access to the numeric characters it found by themselves.
Go has first class support for regular expressions via its regexp package.
For example,
package main
import (
"fmt"
)
func main() {
input := "3d6"
i := int(input[0] - '0')
fmt.Println(i)
}
Playground: https://play.golang.org/p/061miKcXdIF
Output:
3

string size limit input cin.get() and getline()

In this project the user can type in a text(maximum 140 characters).
so for this limitation I once used getline():
string text;
getline(cin, text);
text = text.substr(1, 140);
but in this case the result of cout << text << endl; is an empty string.
so I used cin.get() like:
cin.get(text, 140);
this time I get this error: no matching function for call to ‘std::basic_istream::get(std::__cxx11::string&, int)’
note that I have included <iostream>
so the question is how can I fix this why is this happening?
Your first approach is sound with one correction - you need to use
text = text.substr(0, 140);
instead of text = text.substr(1, 140);. Containers (which includes a string) in C/C++ start with index 0 and you are requesting the string to be trimmed from position 1. This is perfectly fine, but if the string happens to be only one character long, calling text.substr(1, 140); will not necessarily cause the program to crash, but will not end up in the desired output either.
According to this source, substr will throw an out of range exception if called with starting position larger than string length. In case of a one character string, position 1 would be equal to string length, but the return value is not meaningful (in fact, it may even be an undefined behavior but I cannot find a confirmation of this statement - in yours and my case, calling it returns an empty string). I recommend you test it yourself in the interactive coding section following the link above.
Your second approach tried to pass a string to a function that expected C-style character arrays. Again, more can be found here. Like the error said, the compiler couldn't find a matching function because the argument was a string and not the char array. Some functions will perform a conversion of string to char, but this is not the case here. You could convert the string to char array yourself, as for instance described in this post, but the first approach is much more in line with C++ practices.
Last note - currently you're only reading a single line of input, I assume you will want to change that.

Ruby: What does unpack("C") actually do?

From the docs, unpack does:
Decodes str (which may contain binary data) according to the format
string, returning an array of each value extracted.
And the "C" format means 8-bit unsigned (unsigned char).
But what does this actually end up doing to the string I input? What does the result mean, and if I had to do it by hand, how would I go about doing that?
It converts each subsequent char to it’s integer ordinal as String#ord does. That said,
string.unpack 'C*'
is an exact equivalent of
string.each_char.map(&:ord)
But what does this actually end up doing to the string I input
It doesn't do anything to the input. And the input is not really a string here. It's typed as a string, but it is really a buffer of binary data, such as you might receive by networking, and your goal is to extract that data into an array of integers. Example:
s = "\01\00\02\03"
arr = s.unpack("C*")
p(arr) # [1,0,2,3]
That "string" would be meaningless as a string of text, but it is quite viable as a data buffer. Unpacking it allows you examine the data.

How to convert byte array to string in Go [duplicate]

This question already has answers here:
How do I convert [Size]byte to string in Go?
(8 answers)
Closed 2 years ago.
[]byte to string raises an error.
string([]byte[:n]) raises an error too.
By the way, for example, sha1 value to string for filename.
Does it need utf-8 or any other encoding set explicitly?
Thanks!
The easiest method I use to convert byte to string is:
myString := string(myBytes[:])
The easiest way to convert []byte to string in Go:
myString := string(myBytes)
Note: to convert a "sha1 value to string" like you're asking, it needs to be encoded first, since a hash is binary. The traditional encoding for SHA hashes is hex (import "encoding/hex"):
myString := hex.EncodeToString(sha1bytes)
In Go you convert a byte array (utf-8) to a string by doing string(bytes) so in your example, it should be string(byte[:n]) assuming byte is a slice of bytes.
I am not sure that i understand question correctly, but may be:
var ab20 [20]byte = sha1.Sum([]byte("filename.txt"))
var sx16 string = fmt.Sprintf("%x", ab20)
fmt.Print(sx16)
https://play.golang.org/p/haChjjsH0-
ToBe := [6]byte{65, 66, 67, 226, 130, 172}
s:=ToBe[:3]
// this will work
fmt.Printf("%s",string(s))
// this will not
fmt.Printf("%s",string(ToBe))
Difference : ToBe is an array whereas s is a slice.
First you're getting all these negatives reviews because you didn't provided any code.
Second, without a good example. This is what i'd do
var Buf bytes.Buffer
Buf.Write([]byte)
myString := Buf.String()
Buf.Reset() // Reset the buffer to reuse later
or better yet
myString := string(someByteArray[:n])
see here also see #JimB's comment
That being said if you help that targets your program, please provide and example of what you've tried, the expect results, and error.
We can just guess what is wrong with your code because no meaningful example is provided. But first what I see that string([]byte[:n]) is not valid at all. []byte[:n] is not a valid expression because no memory allocated for the array. Since byte array could be converted to string directly I assume that you have just a syntax error.
Shortest valid is fmt.Println(string([]byte{'g', 'o'}))

Resources