Julia之初体验(八)中文字符

中文一般采用Unicode和 UTF-8编码。

julia> s = "\u2200 x \u2203 y"
"∀ x ∃ y"

julia> p="你是好人"
"你是好人"

把UTF-8(中文)字符串切片时到注意:字符∀是三个字节字符,因此索引2和3无效,下一个字符的索引为4;该下一个有效索引可以由nextind(s,1)计算,其后的下一个索引可以由nextind(s,4)计算,依此类推。

julia> s[1]
'∀': Unicode U+2200 (category Sm: Symbol, math)

julia> s[2]
ERROR: StringIndexError("∀ x ∃ y", 2)
[...]

julia> s[3]
ERROR: StringIndexError("∀ x ∃ y", 3)
Stacktrace:
[...]

julia> s[4]
' ': ASCII/Unicode U+0020 (category Zs: Separator, space)
julia> s[end-1]
' ': ASCII/Unicode U+0020 (category Zs: Separator, space)

julia> s[end-2]
ERROR: StringIndexError("∀ x ∃ y", 9)
Stacktrace:
[...]

julia> s[prevind(s, end, 2)]
'∃': Unicode U+2203 (category Sm: Symbol, math)
julia> s[1:1]
"∀"

julia> s[1:2]
ERROR: StringIndexError("∀ x ∃ y", 2)
Stacktrace:
[...]

julia> s[1:4]
"∀ "

julia> p[1]
'你': Unicode U+4F60 (category Lo: Letter, other)

julia> p[2]
ERROR: StringIndexError("你是好人", 2)
Stacktrace:
 [1] string_index_err(::String, ::Int64) at .\strings\string.jl:12
 [2] getindex_continued(::String, ::Int64, ::UInt32) at .\strings\string.jl:220
 [3] getindex(::String, ::Int64) at .\strings\string.jl:213
 [4] top-level scope at none:0

julia> p[4]
'是': Unicode U+662F (category Lo: Letter, other)

为了不出错,还是用迭代器吧。这里面把错误的地方忽略了。

julia> for i = firstindex(s):lastindex(s)
           try
               println(s[i])
           catch
               # ignore the index error
           end
       end

还有一个更好的方法,字符串本来就可以作为迭代器使用。注意:for c in s这个后面没有冒号,与python不同。

julia> for c in s
           println(c)
       end
∀

x

∃

y

julia> for i in p
       print(i)
       end
你是好人


python>for c in s:
           print(c)
∀

x

∃

y

如果需要获取字符串的有效索引,则可以使用nextind和prevind函数递增/递减到下一个/上一个有效索引。 还可以使用eachindex函数来迭代有效的字符索引。collect()函数是用来创建array。

julia> collect(eachindex(s))
7-element Array{Int64,1}:
  1
  4
  5
  6
  7
 10
 11

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bowen2006

你的鼓励是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值