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

7

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

类似于indexof("bc", "abcde")这样的方法吗?

1个回答

11
您可以使用 findfirstfindlast 函数分别查找字符串中子字符串的第一个和最后一个出现位置。
julia> findfirst("bc", "abcde")
2:3

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

findfirstfindlast 会返回一个范围对象,涵盖子字符串在字符串中出现的开头和结尾,如果字符串中没有该子字符串,则返回 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

还有findnextfindprev函数。 findnext找到给定位置后的第一个子字符串出现,而findprev找到给定位置前的最后一个出现。


请注意,findfirstfindlastfindnextfindprev不仅用于在字符串中搜索,还可用于在其他集合(如数组)中搜索。


而且 findall。(编辑:哦,实际上 findall 不适用于字符串搜索。) - DNF
findall 在 git 主分支上适用于字符串,将在 Julia 1.3 中发布。 - Milan Bouchet-Valat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接