Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of substring in Julia

Tags:

julia

How to find index of substring bc in the string abcde?

Something like indexof("bc", "abcde")?

like image 316
Alex Craft Avatar asked Jun 07 '19 05:06

Alex Craft


1 Answers

You can use findfirst or findlast to find the position of the first or the last occurrence of a substring in a string, respectively.

julia> findfirst("bc", "abcde")
2:3

julia> findlast("bc", "abcdebcab")
6:7

findfirst and findlast will return a range object covering the beginning and the ending of the occurrence if the substring occurs in the string, or nothing otherwise. For the first index of the range, you can use result[1] or first(result).

result = findfirst(patternstring, someotherstring)

if isnothing(result)
    # handle the case where there is no occurrence
else
    index = result[1]
    ...
end

There are also findnext and findprev functions. findnext finds the first occurrence of the substring after a given position, whereas findprev finds the last occurrence before a given position.


Note that findfirst, findlast, findnext or findprev are used not just to search in a string but also to search in other collections like arrays.

like image 139
hckr Avatar answered Oct 15 '22 09:10

hckr