How to convert string to tuple in Erlang?
A = "{"hi","how"}"
And I want it to converted into
B = {"hi","how"}.
When I call function list_to_tuple(A) it gives output:
{123,60,60,34,106,105,100,34,62,62,44,34,104,105,34,125}
rather than {"hi","how"}.
You should use erl_scan module to tokenize the string and erl_parse to convert the tokens to a erlang term.
% Note the '.' at the end of the expression inside string.
% The string has to be a valid expression terminated by a '.'.
1> Str = "{\"x\",\"y\"}.".
"{\"x\",\"y\"}."
2> {ok, Ts, _} = erl_scan:string(Str).
{ok,[{'{',1},
{string,1,"x"},
{',',1},
{string,1,"y"},
{'}',1},
{dot,1}],
1}
3> {ok, Tup} = erl_parse:parse_term(Ts).
{ok,{"x","y"}}
4> Tup.
{"x","y"}
Related
I have to convert a backslash string into char, but it seems that casting doesn't exist like in java:
String msg = (Char) new_msg
I have to convert string values like "\t", "\n", "\000"-"\255" to char.
I would first start questioning why you have a single character string in the first place, and whether you can be sure that that is what you actually have. But given that it is, you can get a char from a string, whether it's in the first position or any other, using either String.get, or the more convenient string indexing operator:
let s = "\t"
let c: char = String.get s 0
let c: char = s.[0]
But note that these will both raise an Invalid_argument exception if there is no character at that position, such as if the string is empty, for example.
As an addendum to glennsl's answer, both methods will raise an Invalid_argument exception if the string is empty. If you were writing a function to get the first char of a string, you might use the option type to account for this.
let first_char_of_string s =
try Some s.[0]
with Invalid_argument _ -> None
In various languages, hex values shows as \xhh values in a string literal by using the \x escape sequence
I using encrypting library in lua and hex ouptut is like:
e6dd6bf41a97b89980b2bc2e838bd1bb746b83139b4c1e7c73bdedcc18a01ec24e26703a60cc19d29750c22084470da889e67375afcd9b12595748f6b6ce2d7b436d56ab84e70c819ef52b1edf63148b0ee2cce672ff4d57115c7b51abaaf8a7
but in python library output is:
\xe6\xddk\xf4\x1a\x97\xb8\x99\x80\xb2\xbc.\x83\x8b\xd1\xbbtk\x83\x13\x9bL\x1e|s\xbd\xed\xcc\x18\xa0\x1e\xc2N&p:`\xcc\x19\xd2\x97P\xc2 \x84G\r\xa8\x89\xe6su\xaf\xcd\x9b\x12YWH\xf6\xb6\xce-{CmV\xab\x84\xe7\x0c\x81\x9e\xf5+\x1e\xdfc\x14\x8b\x0e\xe2\xcc\xe6r\xffMW\x11\\{Q\xab\xaa\xf8\xa7
how can i convert Hex number to Hex escaped sequence?
Here is an example code, some characters may fall out, but the gist is this:
local s= [[e6dd6bf41a97b89980b2bc2e838bd1bb746b83139b4c1e7c73bdedcc18a01ec24e26703a60cc19d29750c22084470da889e67375afcd9b12595748f6b6ce2d7b436d56ab84e70c819ef52b1edf63148b0ee2cce672ff4d57115c7b51abaaf8a7]]
function escape (s)
return string.gsub(s, '..', function (c)
local ch = tonumber(c,16)
if ch==10 then return '\\n'
elseif ch==13 then return '\\r' -- 9 and \\t ?
elseif ch==92 then return '\\\\'
elseif 0x1F<ch and ch<0x7f then return string.char(ch)
else return string.format("\\x%s", c)
end
end)
end
print (escape (s) )
maybe there are more elegant solutions with definition of exception characters.
In the example, everything works fine. But they do not use the variable a and immediately display it https://play.golang.org/p/O0XwtQJRej
But I have a problem:
package main
import (
"fmt"
"strings"
)
func main() {
str := "fulltext"
var slice []string
slice = strings.Split(str , "")
fmt.Printf("anwer: ", slice)
}
Whence in the answer there are superfluous characters, for example
%! (EXTRA [] string =
P.S. I know that I need to use append to add elements to the slice, but now I do not understand how to apply append here.
UP:
Now I have the answer:
anwer: %!(EXTRA []string=[f u l l t e x t])
But I need just:
[f u l l t e x t]
But I do not understand how I should change my code?
The problem is not with the assignment of the return value of strings.Split() to the local variable slice, which is totally fine.
The problem is that you used fmt.Printf() which expects a format string, and based on that format string it formats / substitutes expected parameters. Since your format string does not contain any verbs, that fmt.Printf() call expects no parameters, yet you pass it one, so it signals this with those extra characters (kind of error string).
Provide a valid format string where you indicate you will supply 1 parameter, a slice:
fmt.Printf("answer: %v", slice)
With this, the output is:
answer: [f u l l t e x t]
Or alternatively use fmt.Println(), which does not expect a format string:
fmt.Println("answer:", slice)
(Note that there is no space after the colon, as fmt.Println() adds a space between 2 values if one of them is of type string).
Output is the same. Try the examples on the Go Playground.
Staying with fmt.Printf(), when the parameter involves string values, the %q verb is often more useful, as that will print quoted string values, much easier to spot certain mistakes (e.g. invisible characters, or if a string contains spaces, it will become obvious):
fmt.Printf("answer: %q\n", slice)
Output of this (try it on the Go Playground):
answer: ["f" "u" "l" "l" "t" "e" "x" "t"]
If you'd wanted to append the result of a function call, this is how it could look like:
slice := []string{"initial", "content"}
slice = append(slice, strings.Split(str, "")...)
fmt.Printf("answer: %q\n", slice)
And now the output (try it on the Go Playground):
answer: ["initial" "content" "f" "u" "l" "l" "t" "e" "x" "t"]
Give to printf the expected format, in most cases, %v is fine.
package main
import (
"fmt"
"strings"
)
func main() {
str := "fulltext"
var slice []string
slice = strings.Split(str, "")
fmt.Printf("anwer: %v", slice)
}
see https://golang.org/pkg/fmt/ for more info.
In julia, Char and String are not comparable.
julia> 'a' == "a"
false
How can I convert a Char value to a String value?
I have tried the following functions, but none of them work.
julia> convert(String, 'a')
ERROR: MethodError: Cannot `convert` an object of type Char to an object of type String
julia> String('a')
ERROR: MethodError: Cannot `convert` an object of type Char to an object of type String
julia> parse(String, 'a')
ERROR: MethodError: no method matching parse(::Type{String}, ::Char)
The way is
string(c)
e.g.
julia> string('🍕')
"🍕"
The string function works to turn anything into its string representation, in the same way it would be printed. Indeed
help?> string
search: string String stringmime Cstring Cwstring RevString readstring
string(xs...)
Create a string from any values using the print function.
julia> string("a", 1, true)
"a1true"
Just wanted to add that the uppercase String constructor can be successfully used on Vector{Char}, just not on a single char, for which you'd use the lowercase string function. The difference between these two really got me confused.
In summary:
To create a char vector from a string: a = Vector{Char}("abcd")
To create a string from a char vector: s = String(['a', 'b', 'c', 'd'])
To create a string from a single char: cs = string('a')
I want to use following function in my code. I want it to take given string, cut all leading zeros and return a string without the leading zeros. For example I give it '00023' and it shall return '23___' (_ is space)
I have this function in my code:
function cut_zeros(string)
implicit none
character(5) :: cut_zeros, string
integer:: string_limit, i
string_limit = 5
do i= 1, string_limit
if (string(i)/='0') then
cut_zeros = string(i : string_limit)
exit
endif
enddo
end function cut_zeros
I really don't know what problem the compiler has. It gives this information:
cut_zeros = string(i : string_limit)
1
Error: Syntax error in argument list at (1)
I also have another question? Is it possible to make the function assumed length? So that I can pass a string of any length to it? As far as I understand it is not possible, because the return value of a function cannot be assumed length, right?
The error message is actually misleading. The error happens one line above: to compare the i-th character, you need to use string(i:i). If you change that line to
if (string(i:i)/='0') then
the code works as expected.
For the second part of your question, you can use assumed length strings! You can simply set the length of the return value to the length of the input string:
function cut_zeros(string)
implicit none
character(*) :: string
character(len=len(string)) :: cut_zeros
integer:: string_limit, i
string_limit = len(string)
do i= 1, string_limit
if (string(i:i)/='0') then
cut_zeros = string(i : string_limit)
exit
endif
enddo
end function cut_zeros
Here, the length of the return string is chosen that if no zeroes are removed, it still has a valid length. Note that you will require an interface to handle assumed length dummy arguments.
To crop the output string to the exact length required you would need allocatable strings which is not fully supported by all compilers:
function cut_zeros(string)
implicit none
character(*) :: string
character(len=:),allocatable :: cut_zeros
integer:: string_limit, i
string_limit = len(string)
do i= 1, string_limit
if (string(i:i)/='0') then
allocate( character(len=string_limit-i+1) :: cut_zeros )
cut_zeros = string(i : string_limit)
exit
endif
enddo
end function cut_zeros
Or you could use Fortran's existing capabilities
CHARACTER(6) :: src = '002305'
CHARACTER(LEN(src)) :: dest
...
dest = src(SCAN(src,'123456789'):)
! now dest is '2305__'
This only works if the first non-0 character is another digit, if you have other characters to worry about extend the set used in the 2nd argument to SCAN.
The syntax for a substring reference requires the separating colon, i.e. you want string(i:i). If you don't have that colon, the compiler considers that syntax to be a function reference (it knows it isn't an array reference, because you didn't declare string as an array).
You don't want an assumed length function. Such a thing exists, but they are an anachronism that is best forgotten. What you may want is an automatic length function, where the length of the function result depends on the input.
FUNCTION cut_zeros(string)
CHARACTER(*), INTENT(IN) :: string
! The length of the function result is the same as the length
! of the argument.
CHARACTER(LEN(string)) :: cut_zeros
A function with an automatic result requires an explicit interface in any scope where it is referenced. Best off putting it in a module, and USE'ing the module.