在Julia中查找子字符串的索引

Ale*_*hin 4 julia

如何在字符串bc中找到子字符串的索引abcde

indexof("bc", "abcde")什么?

hck*_*ckr 6

您可以使用findfirstfindlast查找字符串中子字符串的第一个或最后一个出现的位置。

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

julia> findlast("bc", "abcdebcab")
6:7
Run Code Online (Sandbox Code Playgroud)

findfirst并且findlast如果子字符串出现在字符串中,则返回一个范围对象,该对象覆盖事件的开始和结束,nothing否则。对于范围的第一个索引,可以使用result[1]first(result)

result = findfirst(patternstring, someotherstring)

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

也有findnextfindprev功能。findnext在给定位置之后查找子字符串的第一个匹配项,而findprev在给定位置之前查找子字符串的最后一个匹配项。


需要注意的是findfirstfindlastfindnextfindprev使用不只是在一个字符串搜索还能在其他收藏品一样的阵列搜索。