您可以使用findfirst
或findlast
查找字符串中子字符串的第一个或最后一个出现的位置。
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)
也有findnext
和findprev
功能。findnext
在给定位置之后查找子字符串的第一个匹配项,而findprev
在给定位置之前查找子字符串的最后一个匹配项。
需要注意的是findfirst
,findlast
,findnext
或findprev
使用不只是在一个字符串搜索还能在其他收藏品一样的阵列搜索。