如何在字符串abcde
中找到子字符串bc
的索引位置?
类似于indexof("bc", "abcde")
这样的方法吗?
findfirst
或 findlast
函数分别查找字符串中子字符串的第一个和最后一个出现位置。julia> findfirst("bc", "abcde")
2:3
julia> findlast("bc", "abcdebcab")
6:7
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
还有findnext
和findprev
函数。 findnext
找到给定位置后的第一个子字符串出现,而findprev
找到给定位置前的最后一个出现。
请注意,findfirst
,findlast
,findnext
或findprev
不仅用于在字符串中搜索,还可用于在其他集合(如数组)中搜索。
findall
。(编辑:哦,实际上findall
不适用于字符串搜索。) - DNFfindall
在 git 主分支上适用于字符串,将在 Julia 1.3 中发布。 - Milan Bouchet-Valat