Converting a string into a string of zeroes and ones on basis of some test

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)
#returns "000100"

Here I need to know if there is some functions with similar behavior to my_fun()

Probably you want a comprehension?

julia> bits = [i in vowels for i in string]
6-element Array{Bool,1}:
 0
 0
 0
 1
 0
 0
1 Like

If you want a String result:

julia> map(c -> '0' + in(c, vowels), "string") 
"000100"

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 < 64:

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)
    end
    return n
end

which gives

julia> n = tobits(c -> c in vowels, string)
0x0000000000000008

julia> bitstring(n)
"0000000000000000000000000000000000000000000000000000000000001000"

(I used Iterators.reverse so that bit i corresponds to character i+1, where i=0 is the least-significant bit.)

2 Likes

Yes that’s exactly what I want thanks!