How to find index of substring bc in the string abcde?
Something like indexof("bc", "abcde")?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With