Amartya Barua
Amartya Barua

Reputation: 155

Strings in Julia

I am playing with Julia and tried to run the following function. Can someone please tell me why I cannot see the last word "programming" in the terminal. Thanks

function prnt(st)
    emptyArr = []
    emptySt = ""
    id = 1

    for char in st
        if (char != ' ' && char != '\n' && char != '\r')
            emptySt = emptySt * char
        else
            print(emptySt)
            emptySt = ""
        end
    end
end

prnt("this is programming")

Upvotes: 1

Views: 77

Answers (1)

longemen3000
longemen3000

Reputation: 1313

i just added a little debugging println to see whats happening:

function prnt(st)
       emptyArr = []
           emptySt = ""
       id = 1

       for char in st
        println(char) #debug statement
           if (char != ' ' && char != '\n' && char != '\r')
               emptySt = emptySt * char
           else
               print(emptySt)
               emptySt = ""
           end
       end
   end

the result was this:

julia> prnt("this is programming")

t
h
i
s

thisi
s

isp
r
o
g
r
a
m
m
i
n
g

adding a print(emptySt) at the end of the loop works fine:

function prnt(st)
       emptyArr = []
           emptySt = ""
       id = 1

       for char in st
           if (char != ' ' && char != '\n' && char != '\r')
               emptySt = emptySt * char
           else
               print(emptySt)
               emptySt = ""
           end
       end
print(emptySt) #extra print here
   end

and this is the result:

julia> prnt("this is programming")
thisisprogramming

an easier way to do this is using the replace function:

function prnt2(st)
    println(replace(st,r" |\n|\r"=>"")) #using a regular expression (r"")
end

The result:

julia> prnt("this is programming")
thisisprogramming

Upvotes: 2

Related Questions