Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia Int Value of a String

I'm fairly new to the Julia language and am struggling to find the integer value of a string.

I know that calling int('a') will return the value I'm looking for, but I cannot figure out how to do the same for int("a").

Is there a way to convert a string value to a character?

UPDATE: Yes, the solution you provided does work, but not in my case. I probably should have been more specific. Here is what my array of strings looks like

array = ["12", "13", "14"] ["16", "A"]

array[2][2] returns "A" not 'A'

like image 428
user1748681 Avatar asked Mar 02 '14 20:03

user1748681


People also ask

How to convert string to integer in Julia?

The string input is taken from the user using the readline () method of Julia. Next, the parse () method is used to convert the String into Integer datatype with the given base (here octal). The typeof () method outputs the datatype of the resulting integer.

What is the use of string() function in Julia?

The string () is an inbuilt function in julia which is used to convert a specified integer to a string in the given base. n::Integer: Specified integer. base::Integer: Specified base in which conversion are going to be performed. pad::Integer: It is number of characters present in the returned string.

How do I extract a character from a string in Julia?

If you want to extract a character from a string, you index into it: Many Julia objects, including strings, can be indexed with integers. The index of the first element (the first character of a string) is returned by firstindex (str), and the index of the last element (character) with lastindex (str).

What is the default string type in Julia?

In Julia, the built-in concrete type used for strings as well as string literals is String which supports full range of Unicode characters via the UTF-8 encoding. All the string types in Julia are subtypes of the abstract type AbstractString.


2 Answers

Strings are represented internally as an array of Uint8, so for ASCIIStrings the following works:

julia> "Hello".data
5-element Array{Uint8,1}:
 0x48
 0x65
 0x6c
 0x6c
 0x6f

The definition of a character is more complicated for Unicode, however, so use this with caution.

like image 96
tholy Avatar answered Sep 25 '22 21:09

tholy


From the "String Basics" section of the Julia manual:

julia> str = "Hello, world.\n"
"Hello, world.\n"

If you want to extract a character from a string, you index into it:

julia> str[1]
'H'

julia> str[6]
','

julia> str[end]
'\n'

So you can get the character at index 1, and then pass that to int.

like image 24
ruakh Avatar answered Sep 24 '22 21:09

ruakh