gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:10:49 24 4
gpt4 key购买 nike

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

类似 indexof("bc", "abcde") ?

最佳答案

您可以使用 findfirst findlast 分别查找子字符串在字符串中第一次或最后一次出现的位置。

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

还有 findnext findprev 职能。 findnext查找给定位置后第一次出现的子字符串,而 findprev查找给定位置之前的最后一次出现。

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

关于julia - 在 Julia 中查找子字符串的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56488503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com