如何在 Julia 中获取字符串的子字符串?

Moh*_*ari 10 string julia

Julia 中是否有一种方法可以从一个特定角色转移到另一个角色?比如我想获取s="Hello, world"3到9个字符的变量。

# output = 'llo, wo'
Run Code Online (Sandbox Code Playgroud)

Bog*_*ski 12

另一种解决方案仅适用于 ASCII 字符串。然而,正如我前段时间在博客中讨论的那样,Julia在语法中使用字节索引而不是字符索引。如果您想使用字符索引(我假设您从问题的措辞中做到这一点),这里您有一个使用宏的解决方案。getindex

一般来说(不使用上面链接的解决方案)要使用的函数是:chopfirstlast或 用于索引操作previndnextindlength

例如,要获取 3 到 9 的字符,安全语法如下(仅显示几种组合)

julia> str = " Hello! "
" Hello! "

julia> last(first(str, 9), 7)
"Hello! "

julia> chop(str, head=2, tail=length(str)-9)
"Hello! "

julia> chop(first(str, 9), head=2, tail=0)
"Hello! "

julia> str[(:)(nextind.(str, 0, (3, 9))...)]
"Hello! "
Run Code Online (Sandbox Code Playgroud)

但请注意,以下内容是不正确的:

julia> str[3:9]
ERROR: StringIndexError: invalid index [3], valid nearby indices [1]=>'', [5]=>' '
Run Code Online (Sandbox Code Playgroud)

有一个悬而未决的问题,需要变得chop更加灵活,这将简化您的特定索引情况。


Moh*_*ari 1

您可以使用以下方法:

s="Hello, world"

s[3:9]
# output: llo, wo

s[3:end]
# output: llo, world
Run Code Online (Sandbox Code Playgroud)