Is there a way to convert a string into zeroes and ones on the basis of some test like follows?:
vowels = ['a', 'e', 'i', 'o', 'u']
string = "string"
bits = my_fun(i -> (i in vowels), string)
Here I need to know if there is some functions with similar behavior to
Probably you want a comprehension?
julia> bits = [i in vowels for i in string]
If you want a
julia> map(c -> '0' + in(c, vowels), "string")
How can I convert this array to a binary number?
This is a really nice way but I wonder which one will be faster @stevengj’s solution or yours?
I see, what you want is a single integer whose bit patterns match this binary array? Probably the most efficient thing to do is to build up such an integer directly, rather than creating an array first. For example, the following works as long as the number of characters in the string is
function tobits(predicate::Function, s::String)
n = UInt64(0)
len = 0
for c in Iterators.reverse(s)
len += 1
len > 64 && throw(ArgumentError("length of string is > 64"))
n = (n << 1) + predicate(c)
julia> n = tobits(c -> c in vowels, string)
Iterators.reverse so that bit
i corresponds to character
i=0 is the least-significant bit.)
Yes that’s exactly what I want thanks!