Detect space

hi all
i try to detect space in string, if i have

“Hello World , i need to detect the index i , in python i just look for if arr[i] ==” "
put here it doesn’t work.

function lengthOfLastWord(arr)
    i=length(arr)
    count = 0 
    while i>=1 && arr[i] ==" "
        print(arr[i])
        i -=1
    end
    while i>=1 && arr[i] !=" "
        i-=1
        count +=1
    end
    return count
end

arr = "Hello World"
println(lengthOfLastWord(arr))

the output her = 11
it mean he reverse to the beginning and skip on the space between two word.
it should return 5

any help ? thanks a lot for u guys you are helping me a lot

Maybe try this instead:

arr[i] == ' '
2 Likes

work !
thanks

1 Like

You also may be interested in the isspace function:

isspace(arr[i])
4 Likes

It is worth noting that strings in Julia can use variable-length encoding, which means that 1:length(str) == collect(eachindex(str)) may be false.

For example, when applying your function to string "hello ωrold", the result is a StringIndexError. A generic implementation of your function is:

function lengthOfLastWord(str)
	i = findlast(isspace, str)
	if i === nothing
		length(str)
	else
		length(str, nextind(str, i), lastindex(str))
	end
end
4 Likes