Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert any type into String in Julia

Tags:

julia

Using Julia, I'd like to reliably convert any type into type String. There seems to be two ways to do the conversion in v0.5, either the string function or String constructor. The problem is that you need to choose the right one depending upon the input type.

For example, typeof(string(1)) evaluates to String, but String(1) throws an error. On the other hand, typeof(string(SubString{String}("a"))) evaluates to Substring{String}, which is not a subtype of String. We instead need to do String(SubString{String}("a")).

So it seems the only reliable way to convert any input x to type String is via the construct:

String(string(x))

which feels a bit cumbersome.

Am I missing something here?

like image 239
Colin T Bowers Avatar asked Jan 30 '17 04:01

Colin T Bowers


People also ask

How to convert to string in Julia?

Convert an Integer to a String in Julia – string() Function The string() is an inbuilt function in julia which is used to convert a specified integer to a string in the given base. Parameters: n::Integer: Specified integer. base::Integer: Specified base in which conversion are going to be performed.

How do you convert to float in Julia?

In general, one should have a//b == convert(Rational{Int64}, a/b) . The last two convert methods provide conversions from rational types to floating-point and integer types. To convert to floating point, one simply converts both numerator and denominator to that floating point type and then divides.

How do you replace characters in strings in Julia?

The replace() is an inbuilt function in julia that is used to replace a word or character with the specified string or character. Parameters: s::AbstractString: Specified string. pattern=>Word: Pattern is searched from the given sentence and then that pattern is replaced with the word.

How do you know if strings are equal in Julia?

The cmp() is an inbuilt function in julia which is used to return 0 if the both specified strings are having the same length and the character at each index is the same in both strings, return -1 if a is a prefix of b, or if a comes before b in alphabetical order and return 1 if b is a prefix of a, or if b comes before ...


1 Answers

You should rarely need to explicitly convert to String. Note that even if your type definitions have String fields, or if your arrays have concrete element type String, you can still rely on implicit conversion.

For instance, here are examples of implicit conversion:

type TestType
    field::String
end

obj = TestType(split("x y")[1])  # construct TestType with a SubString
obj.field  # the String "x"

obj.field = SubString("Hello", 1, 3)  # assign a SubString
obj.field  # the String "Hel"
like image 180
Fengyang Wang Avatar answered Sep 19 '22 11:09

Fengyang Wang